<!-- eslint-disable vue/valid-template-root, vue/no-unused-vars, vue/multi-word-component-names -->
<template>
  <div class="statistics-view">
    <!-- 头部 -->
    <div class="stats-header">
      <h1 class="page-title">数据统计</h1>
      
      <!-- 时间范围选择器 -->
      <div class="date-range-selector">
        <el-select 
          v-model="timeRange" 
          placeholder="选择时间范围" 
          size="large"
          class="time-select"
        >
          <el-option
            v-for="item in timeRangeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
                </div>
                    </div>

    <!-- 加载状态 -->
    <div v-if="false" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载统计数据中...</p>
                    </div>

    <div v-else class="stats-grid">
      <!-- 恢复独立的物品总花销卡片 -->
      <div class="stats-card total-spending" @click="showCardDetail('total-spending')">
        <div class="card-title">物品总花销</div>
        <div class="card-content total-value">{{ totalSpending }}</div>
        <div class="card-action">查看花销详情</div>
                    </div>
      
      <!-- 综合统计数据卡片 -->
      <div class="stats-card combined-stats" @click="showCardDetail('combined-stats')">
        <div class="card-title">物品综合统计</div>
        <div class="combined-stats-content">
          <div class="combined-stat-item">
            <div class="stat-icon" style="background-color: #0071e322">
              <el-icon style="color: #0071e3"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">总物品数量</div>
              <div class="stat-value">{{ stats.totalItems }}</div>
              <!-- 修复：动态绑定趋势数据和图标 -->
              <div class="stat-trend trend-up" v-if="stats.totalItemsTrend > 0">
                <el-icon><ArrowUp /></el-icon>
                <span>{{ Math.abs(stats.totalItemsTrend) }}%</span>
              </div>
            </div>
          </div>

          <div class="combined-stat-item">
            <div class="stat-icon" style="background-color: #34c75922">
              <el-icon style="color: #34c759"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">总资产价值</div>
              <div class="stat-value">{{ formatCurrency(stats.totalValue) }}</div>
              <!-- 修复：动态绑定趋势数据和图标 -->
              <div class="stat-trend trend-up" v-if="stats.totalValueTrend > 0">
                <el-icon><ArrowUp /></el-icon>
                <span>{{ Math.abs(stats.totalValueTrend) }}%</span>
              </div>
              <!-- 添加下降趋势的处理 -->
              <div class="stat-trend trend-down" v-else-if="stats.totalValueTrend < 0">
                <el-icon><ArrowDown /></el-icon>
                <span>{{ Math.abs(stats.totalValueTrend) }}%</span>
              </div>
            </div>
          </div>
          
          <div class="combined-stat-item">
            <div class="stat-icon" style="background-color: #ff950022">
              <el-icon style="color: #ff9500"><Goods /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">本月新增</div>
              <div class="stat-value">{{ stats.newItemsThisMonth }}</div>
              <!-- 本月新增通常没有趋势，可以移除或添加其他逻辑 -->
            </div>
          </div>
        </div>
      </div>
      
      <!-- 过期物品卡片 -->
      <div 
        class="stats-card" 
        v-for="stat in filteredOverviewStats" 
        :key="stat.id"
        @click="showCardDetail('overview', stat)"
      >
        <div class="card-icon" :style="{ backgroundColor: stat.color + '22' }">
          <el-icon :style="{ color: stat.color }"><component :is="stat.icon" /></el-icon>
        </div>
        <div class="card-content">
          <div class="card-title">{{ stat.label }}</div>
          <div class="card-value">{{ stat.value }}</div>
          <div class="expiry-details">
            <div class="expiry-item">
              <div class="expiry-dot" style="background-color: #ff9500;"></div>
              <span>即将过期: {{ inventoryStore.getExpiringItems?.length || 0 }}</span>
            </div>
            <div class="expiry-item">
              <div class="expiry-dot" style="background-color: #ff3b30;"></div>
              <span>已过期: {{ getExpiredCount() }}</span>
            </div>
          </div>
        </div>
        <div class="card-trend" :class="{'trend-up': stat.trend > 0, 'trend-down': stat.trend < 0}" v-if="stat.trend !== 0">
          <el-icon v-if="stat.trend > 0"><ArrowUp /></el-icon>
          <el-icon v-else><ArrowDown /></el-icon>
          <span>{{ Math.abs(stat.trend) }}%</span>
        </div>
      </div>

      <!-- 物品购买渠道分布图 -->
      <div class="stats-card chart-card" @click="showCardDetail('channel-distribution')">
        <div class="card-title">购买渠道分布</div>
        <div class="chart-container">
          <div class="pie-chart" ref="channelPieChartRef"></div>
          <div v-if="false" class="chart-placeholder">
            <div class="placeholder-icon"><el-icon><Location /></el-icon></div>
            <div class="placeholder-text">位置分布数据加载中...</div>
          </div>
          <div class="chart-legend">
            <div v-for="(item, index) in channelCategoryList.slice(0, 5)" :key="item.name" class="legend-item">
              <span class="color-dot" :style="{backgroundColor: item.color}"></span>
              <span class="legend-name">{{ item.name }}</span>
              <span class="legend-value">{{ item.amount }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 花销排行榜 -->
      <div class="stats-card rank-card" @click="showCardDetail('spending-rank')">
        <div class="card-title">物品花销排行</div>
        <div class="rank-list">
          <div v-for="(item, idx) in spendingRankList.slice(0, 5)" :key="item.name" class="rank-item">
            <div class="rank-index" :class="{'top-rank': idx < 3}">{{ idx+1 }}</div>
            <div class="rank-info">
              <div class="rank-name">{{ item.name }}</div>
              <div class="rank-value">{{ item.amount }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 持有天数排行榜 -->
      <div class="stats-card rank-card" @click="showCardDetail('holding-days-rank')">
        <div class="card-title">持有天数排行</div>
        <div class="rank-list">
          <div v-for="(item, idx) in holdingDaysRankList.slice(0, 5)" :key="item.name" class="rank-item">
            <div class="rank-index" :class="{'top-rank': idx < 3}">{{ idx+1 }}</div>
            <div class="rank-info">
              <div class="rank-name">{{ item.name }}</div>
              <div class="rank-value">{{ item.days }}天</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 类别分布图 -->
      <div class="stats-card chart-card" @click="showCardDetail('category-distribution')">
        <div class="card-title">物品类别分布</div>
        <div class="chart-container">
          <div class="pie-chart" ref="categoryChartRef"></div>
          <div v-if="false" class="chart-placeholder">
            <div class="placeholder-icon"><el-icon><DataAnalysis /></el-icon></div>
            <div class="placeholder-text">类别分布数据加载中...</div>
          </div>
          <div class="chart-legend">
            <div v-for="(item, index) in stats.topCategories.slice(0, 5)" :key="item.name" class="legend-item">
              <span class="color-dot" :style="{backgroundColor: getCategoryColor(item.name)}"></span>
              <span class="legend-name">{{ item.name }}</span>
              <span class="legend-value">{{ item.count }}件</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 位置分布图 -->
      <div class="stats-card chart-card" @click="showCardDetail('location-distribution')">
        <div class="card-title">储存位置分布</div>
        <div class="chart-container">
          <div class="pie-chart" ref="locationChartRef"></div>
          <div v-if="false" class="chart-placeholder">
            <div class="placeholder-icon"><el-icon><Location /></el-icon></div>
            <div class="placeholder-text">位置分布数据加载中...</div>
          </div>
          <div class="chart-legend">
            <div v-for="(item, index) in (stats.topLocations || []).slice(0, 5)" :key="item.name" class="legend-item">
              <span class="color-dot" :style="{backgroundColor: getLocationColor(item.name)}"></span>
              <span class="legend-name">{{ item.name }}</span>
              <span class="legend-value">{{ item.count }}件</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 月度支出趋势 -->
      <div class="stats-card chart-card" @click="showCardDetail('monthly-spending')">
        <div class="card-title">月度支出趋势</div>
        <div class="chart-container">
          <div class="line-chart" ref="spendingTrendChartRef">
            <div class="monthly-trend">
              <div v-for="(item, index) in monthlySpendingData" :key="index" class="trend-bar">
                <div class="trend-bar-fill" :style="{height: (item.value / maxMonthlySpending * 100) + '%', backgroundColor: getMonthColor(index)}"></div>
                <div class="trend-month">{{ item.month }}</div>
              </div>
            </div>
          </div>
          <div v-if="false" class="chart-placeholder">
            <div class="placeholder-icon"><el-icon><DataLine /></el-icon></div>
            <div class="placeholder-text">月度支出趋势数据加载中...</div>
          </div>
        </div>
      </div>
      
      <!-- 物品状态分布 -->
      <div class="stats-card chart-card" @click="showCardDetail('status-distribution')">
        <div class="card-title">物品状态分布</div>
        <div class="chart-container">
          <div class="pie-chart" ref="statusChartRef"></div>
          <div v-if="false" class="chart-placeholder">
            <div class="placeholder-icon"><el-icon><DataAnalysis /></el-icon></div>
            <div class="placeholder-text">状态分布数据加载中...</div>
          </div>
          <div class="chart-legend">
            <div v-for="(item, index) in statusDistribution.data.slice(0, 5)" :key="item.name" class="legend-item">
              <span class="color-dot" :style="{backgroundColor: item.color}"></span>
              <span class="legend-name">{{ item.name }}</span>
              <span class="legend-value">{{ item.count }}件</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 使用频率分布（新增） -->
      <div class="stats-card chart-card" @click="showCardDetail('usage-distribution')">
        <div class="card-title">使用频率分布</div>
        <div class="chart-container">
          <div class="pie-chart" ref="usageChartRef"></div>
          <div v-if="false" class="chart-placeholder">
            <div class="placeholder-icon"><el-icon><DataAnalysis /></el-icon></div>
            <div class="placeholder-text">使用频率数据加载中...</div>
          </div>
        </div>
      </div>
      
      <!-- 物品评分雷达图（新增） -->
      <div class="stats-card chart-card" @click="showCardDetail('item-rating')">
        <div class="card-title">物品评分分析</div>
        <div class="chart-container">
          <div class="radar-chart" ref="ratingChartRef"></div>
          <div v-if="false" class="chart-placeholder">
            <div class="placeholder-icon"><el-icon><Star /></el-icon></div>
            <div class="placeholder-text">评分数据加载中...</div>
          </div>
        </div>
      </div>


    </div>

    <!-- 卡片详情模态框 -->
    <transition name="modal" :duration="{ enter: 400, leave: 300 }">
      <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
        <div class="modal-container" :class="{'modal-loading': detailLoading}">
          <div class="modal-header">
            <h2 class="modal-title">{{ currentCardTitle }}</h2>
            <button class="modal-close" @click="closeModal">
              <el-icon><Close /></el-icon>
            </button>
          </div>

          <div v-if="detailLoading" class="modal-loading-indicator">
            <div class="loading-spinner"></div>
            <p>加载详细数据中...</p>
          </div>
          
          <div v-else class="modal-content">
            <!-- 总花销详情 -->
            <template v-if="currentCardType === 'total-spending'">
              <div class="detail-section">
                <div class="detail-header">
                  <!-- Removed h3 -->
                  <div class="period-selector">
                    <el-radio-group v-model="detailPeriod" size="small">
                      <el-radio-button label="month">月度</el-radio-button>
                      <el-radio-button label="quarter">季度</el-radio-button>
                      <el-radio-button label="year">年度</el-radio-button>
                    </el-radio-group>
                  </div>
                </div>
                
                <div class="big-number-display">
                  <div class="big-number">{{ totalSpending }}</div>
                  <div class="big-number-label">总花销</div>
                </div>
                
                <div class="detail-chart-container" ref="detailSpendingChartRef"></div>
                
                <div class="detail-data-table">
                  <table>
                    <thead>
                      <tr>
                        <th>时间</th>
                        <th>花销金额</th>
                        <th>占比</th>
                        <th>环比增长</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="item in stats.monthlySpending.slice(0, 6)" :key="item.month">
                        <td>{{ item.month }}</td>
                        <td>{{ item.value }}</td>
                        <td>{{ Math.floor(item.value / 15000 * 100) }}%</td>
                        <td :class="{'text-green': item.value > 1500, 'text-red': item.value < 1500}">
                          {{ item.value > 1500 ? '+' : '' }}{{ Math.floor((item.value - 1500) / 1500 * 100) }}%
                        </td>
                      </tr>
                    </tbody>
                  </table>
        </div>

                <!-- 添加花销分布图表和数据网格 -->
                <h3 style="margin-top: 30px; margin-bottom: 15px;">花销分布详情</h3>
                <div class="detail-chart-large" ref="detailDistributionChartRef"></div>
                <div class="detail-data-grid">
                  <div v-for="item in spendingCategoryList" :key="item.name" class="detail-data-card">
                    <div class="data-card-header" :style="{ backgroundColor: item.color + '22' }">
                      <div class="data-card-color" :style="{ backgroundColor: item.color }"></div>
                      <div class="data-card-title">{{ item.name }}</div>
                    </div>
                    <div class="data-card-body">
                      <div class="data-card-amount">{{ item.amount }}</div>
                      <div class="data-card-percent">{{ item.percent }}%</div>
                    </div>
                  </div>
                </div>
              </div>
            </template>

            <!-- 物品综合统计详情 -->
            <template v-else-if="currentCardType === 'combined-stats'">
              <div class="detail-section">
                <div class="combined-stats-detail">
                  <div class="detail-data-card total-items">
                    <div class="data-card-header" style="background-color: #0071e322">
                      <div class="data-card-icon">
                        <el-icon style="color: #0071e3"><Document /></el-icon>
                      </div>
                      <div class="data-card-title">总物品数量</div>
                    </div>
                    <div class="data-card-body">
                      <div class="data-card-amount">{{ stats.totalItems }}</div>
                      <div class="data-card-trend trend-up">
                        <el-icon><ArrowUp /></el-icon>
                        <span>同比增长 3%</span>
                      </div>
                    </div>
                    <div class="data-card-chart" ref="itemsTrendChartRef"></div>
                  </div>
                  
                  <div class="detail-data-card total-value">
                    <div class="data-card-header" style="background-color: #34c75922">
                      <div class="data-card-icon">
                        <el-icon style="color: #34c759"><Money /></el-icon>
                      </div>
                      <div class="data-card-title">总资产价值</div>
                    </div>
                    <div class="data-card-body">
                      <div class="data-card-amount">{{ formatCurrency(stats.totalValue) }}</div>
                      <div class="data-card-trend trend-up">
                        <el-icon><ArrowUp /></el-icon>
                        <span>同比增长 5%</span>
                      </div>
                    </div>
                    <div class="data-card-chart" ref="valueTrendChartRef"></div>
                  </div>
                  
                  <div class="detail-data-card new-items">
                    <div class="data-card-header" style="background-color: #ff950022">
                      <div class="data-card-icon">
                        <el-icon style="color: #ff9500"><Goods /></el-icon>
                      </div>
                      <div class="data-card-title">本月新增物品</div>
                    </div>
                    <div class="data-card-body">
                      <div class="data-card-amount">{{ stats.newItemsThisMonth }}</div>
                      <div class="monthly-detail">
                        <div class="monthly-chart" ref="newItemsChartRef"></div>
                        <div class="monthly-stats">
                          <div class="stat-row">
                            <div class="stat-label">平均每日</div>
                            <div class="stat-value">{{ (stats.newItemsThisMonth / 30).toFixed(1) }}</div>
                          </div>
                          <div class="stat-row">
                            <div class="stat-label">占总量比例</div>
                            <div class="stat-value">{{ (stats.newItemsThisMonth / stats.totalItems * 100).toFixed(1) }}%</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div class="detail-data-table">
                    <h4>新增物品类别分布</h4>
                    <table>
                      <thead>
                        <tr>
                          <th>物品类别</th>
                          <th>新增数量</th>
                          <th>占比</th>
                          <th>变化趋势</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td>电子产品</td>
                          <td>5</td>
                          <td>41.7%</td>
                          <td class="text-green">↑ 15%</td>
                        </tr>
                        <tr>
                          <td>厨房用品</td>
                          <td>3</td>
                          <td>25.0%</td>
                          <td class="text-green">↑ 8%</td>
                        </tr>
                        <tr>
                          <td>家具</td>
                          <td>2</td>
                          <td>16.7%</td>
                          <td class="text-red">↓ 5%</td>
                        </tr>
                        <tr>
                          <td>其他</td>
                          <td>2</td>
                          <td>16.7%</td>
                          <td>-</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </template>
            
            <!-- 使用频率分布详情 -->
            <template v-else-if="currentCardType === 'usage-distribution'">
              <div class="detail-section">
                <div class="detail-chart-large" ref="detailUsageChartRef"></div>
                
                <div class="usage-stats-grid">
                  <div v-for="item in usageStats" :key="item.id" class="usage-stat-card" :style="{ borderLeftColor: item.color }">
                    <div class="usage-stat-header">
                      <div class="usage-stat-color" :style="{ backgroundColor: item.color }"></div>
                      <div class="usage-stat-name">{{ item.name }}</div>
                    </div>
                    <div class="usage-stat-count">{{ item.count }}件</div>
                    <div class="usage-stat-percent">{{ (item.count / getTotalItemsFromUsage() * 100).toFixed(1) }}%</div>
                    <div class="usage-stat-action" v-if="item.action">{{ item.action }}</div>
                  </div>
                </div>
                
                <div class="usage-recommendations">
                  <h4>使用建议</h4>
                  <div class="recommendation-list">
                    <div class="recommendation-item">
                      <el-icon class="recommendation-icon"><Warning /></el-icon>
                      <div class="recommendation-content">
                        <div class="recommendation-title">处理过期物品</div>
                        <div class="recommendation-desc">您有 {{ getExpiredCount() }} 件过期物品需要处理</div>
                      </div>
                    </div>
                    <div class="recommendation-item">
                      <el-icon class="recommendation-icon"><InfoFilled /></el-icon>
                      <div class="recommendation-content">
                        <div class="recommendation-title">物品闲置情况</div>
                        <div class="recommendation-desc">有 {{ usageStats.find(s => s.id === 'idle')?.count || 0 }} 件物品已闲置，建议考虑处理</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
            
            <!-- 购买渠道转化详情 -->
            <template v-else-if="currentCardType === 'channel-conversion'">
              <div class="detail-section">
                <div class="detail-chart-large" ref="detailFunnelChartRef"></div>
                
                <div class="conversion-detail-grid">
                  <div v-for="(item, index) in channelConversionData" :key="item.name" class="conversion-card">
                    <div class="conversion-step">步骤 {{ index + 1 }}</div>
                    <div class="conversion-name">{{ item.name }}</div>
                    <div class="conversion-value">{{ item.value }}</div>
                    <div class="conversion-rate" v-if="index > 0">
                      转化率: {{ ((item.value / channelConversionData[index - 1].value) * 100).toFixed(1) }}%
                    </div>
                  </div>
                </div>
                
                <div class="conversion-analysis">
                  <h4>转化分析</h4>
                  <p>从浏览商品到最终收到物品，整体转化率为 {{ (channelConversionData[channelConversionData.length - 1].value / channelConversionData[0].value * 100).toFixed(1) }}%。最大流失发生在加入购物车到提交订单阶段，建议优化这一环节的体验。</p>
                </div>
              </div>
            </template>
            
            <!-- 物品评分分析详情 -->
            <template v-else-if="currentCardType === 'item-rating'">
              <div class="detail-section">
                <!-- 主图表容器 -->
                <div class="detail-chart-large" ref="detailRatingChartRef"></div>
                
                <!-- 移除旧的多维度分解 -->
                <!-- <div class="rating-breakdown"> ... </div> -->

                <!-- 可以添加一个表格显示详细数据 -->
                <div class="detail-data-table" style="margin-top: 30px;">
                  <h4>各类别平均评分详情</h4>
                  <table>
                    <thead>
                      <tr>
                        <th>物品类别</th>
                        <th>性价比</th>
                        <th>耐用性</th>
                        <th>外观</th>
                        <th>实用性</th>
                        <th>满意度</th>
                        <th>评分物品数</th>
                      </tr>
                    </thead>
                    <tbody>
                      <!-- 使用 itemRatingData.value 渲染 -->
                      <tr v-for="item in itemRatingData" :key="item.name">
                        <td>
                          <span class="color-dot" :style="{ backgroundColor: item.color, marginRight: '8px' }"></span>
                          {{ item.name }}
                        </td>
                        <!-- 假设 item.value 是包含5个评分的数组 -->
                        <td v-for="(score, index) in item.value" :key="index">{{ score }}</td>
                        <td>{{ item.count }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </template>

            <!-- 过期物品详情 -->
            <template v-else-if="currentCardType === 'overview' && currentCardData && currentCardData.id === 'expiring'">
              <div class="detail-section">
                <div class="expiry-summary">
                  <div class="expiry-stat-card">
                    <div class="expiry-stat-icon" style="background-color: #ff950022">
                      <el-icon style="color: #ff9500"><Calendar /></el-icon>
                    </div>
                    <div class="expiry-stat-content">
                      <div class="expiry-stat-label">即将过期物品</div>
                      <div class="expiry-stat-value">{{ inventoryStore.getExpiringItems?.length || 0 }}</div>
                      <div class="expiry-stat-desc">建议尽快使用这些物品</div>
                    </div>
                  </div>
                  
                  <div class="expiry-stat-card">
                    <div class="expiry-stat-icon" style="background-color: #ff3b3022">
                      <el-icon style="color: #ff3b30"><Warning /></el-icon>
                    </div>
                    <div class="expiry-stat-content">
                      <div class="expiry-stat-label">已过期物品</div>
                      <div class="expiry-stat-value">{{ getExpiredCount() }}</div>
                      <div class="expiry-stat-desc">建议尽快处理这些物品</div>
                    </div>
                  </div>
                </div>
                
                <div class="expiry-chart-container" ref="expiryChartRef"></div>
                
                <h4 class="expiry-list-title">即将过期物品列表</h4>
                <div class="expiry-item-list">
                  <div v-for="(item, index) in expiringItems" :key="index" class="expiry-item">
                    <div class="expiry-item-name">{{ item.name }}</div>
                    <div class="expiry-item-date">{{ item.expiryDate }}</div>
                    <div class="expiry-item-days">剩余 {{ item.daysLeft }} 天</div>
                    <el-button size="small" type="warning">标记使用</el-button>
                  </div>
                </div>
                
                <h4 class="expiry-list-title">已过期物品列表</h4>
                <div class="expiry-item-list">
                  <div v-for="(item, index) in expiredItems" :key="index" class="expiry-item expired">
                    <div class="expiry-item-name">{{ item.name }}</div>
                    <div class="expiry-item-date">{{ item.expiryDate }}</div>
                    <div class="expiry-item-days">已过期 {{ item.daysExpired }} 天</div>
                    <el-button size="small" type="danger">丢弃物品</el-button>
                  </div>
                </div>
              </div>
            </template>
            
            <!-- 购买渠道分布详情 -->
            <template v-else-if="currentCardType === 'channel-distribution'">
              <div class="detail-section">
                <div class="channel-charts-container">
                  <div class="channel-chart-container" ref="channelDetailChartRef"></div>
                  <div class="channel-funnel-container" ref="detailFunnelChartRef"></div>
                </div>
                
                <div class="channel-stats-grid">
                  <div v-for="item in channelCategoryList" :key="item.name" class="channel-stat-card">
                    <div class="channel-stat-header" :style="{ backgroundColor: item.color + '22' }">
                      <div class="channel-stat-color" :style="{ backgroundColor: item.color }"></div>
                      <div class="channel-stat-name">{{ item.name }}</div>
                    </div>
                    <div class="channel-stat-body">
                      <div class="channel-stat-amount">{{ item.amount }}</div>
                      <div class="channel-stat-percent">{{ item.percent }}%</div>
                    </div>
                  </div>
                </div>
                
                <div class="channel-trend">
                  <h4>渠道花销趋势（近6个月）</h4>
                  <div class="channel-trend-chart" ref="channelTrendChartRef"></div>
                </div>
                
                <div class="channel-table">
                  <h4>各渠道物品购买情况分析</h4>
                  <table>
                    <thead>
                      <tr>
                        <th>渠道名称</th>
                        <th>总花销</th>
                        <th>平均单价</th>
                        <th>物品数量</th>
                        <th>最近购买</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="channel in channelDetails" :key="channel.name">
                        <td>{{ channel.name }}</td>
                        <td>{{ channel.totalSpending }}</td>
                        <td>{{ channel.avgPrice }}</td>
                        <td>{{ channel.itemCount }}</td>
                        <td>{{ channel.lastPurchase }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </template>
            
            <!-- 物品花销排行详情 -->
            <template v-else-if="currentCardType === 'spending-rank'">
              <div class="detail-section">
                <div class="spending-rank-chart" ref="spendingRankChartRef"></div>
                
                <div class="spending-rank-table">
                  <h4>物品花销排行榜（Top 10）</h4>
                  <table>
                    <thead>
                      <tr>
                        <th>排名</th>
                        <th>物品名称</th>
                        <th>花销金额</th>
                        <th>购买日期</th>
                        <th>占总花销比例</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(item, index) in spendingRankList" :key="item.name">
                        <td>
                          <div class="rank-number" :class="{'top-rank': index < 3}">{{ index + 1 }}</div>
                        </td>
                        <td>{{ item.name }}</td>
                        <td>{{ item.amount }}</td>
                        <td>{{ item.purchaseDate }}</td>
                        <td>
                          <div class="percent-bar-container">
                            <div class="percent-bar" :style="{ width: (numericTotalSpending > 0 ? (item.amount / numericTotalSpending * 100) : 0) + '%' }"></div>
                            <span>{{ (numericTotalSpending > 0 ? (item.amount / numericTotalSpending * 100) : 0).toFixed(1) }}%</span>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                
                <div class="spending-category-distribution">
                  <h4>高花销物品类别分布</h4>
                  <div class="spending-category-chart" ref="spendingCategoryChartRef"></div>
                </div>
              </div>
            </template>
            
            <!-- 持有天数排行详情 -->
            <template v-else-if="currentCardType === 'holding-days-rank'">
              <div class="detail-section">
                <div class="holding-days-chart" ref="holdingDaysChartRef"></div>
                
                <div class="holding-days-stats">
                  <div class="stats-card">
                    <div class="stats-card-value">{{ averageHoldingDays }}天</div>
                    <div class="stats-card-label">平均持有天数</div>
                  </div>
                  <div class="stats-card">
                    <div class="stats-card-value">{{ longestHoldingDays }}天</div>
                    <div class="stats-card-label">最长持有天数</div>
                  </div>
                  <div class="stats-card">
                    <div class="stats-card-value">{{ shortestHoldingDays }}天</div>
                    <div class="stats-card-label">最短持有天数</div>
                  </div>
                  <div class="stats-card">
                    <div class="stats-card-value">{{ recentlyAddedItems }}</div>
                    <div class="stats-card-label">30天内新增</div>
                  </div>
                </div>
                
                <div class="holding-days-table">
                  <h4>物品持有天数排行榜（Top 10）</h4>
                  <table>
                    <thead>
                      <tr>
                        <th>排名</th>
                        <th>物品名称</th>
                        <th>已持有天数</th>
                        <th>购买日期</th>
                        <th>使用频率</th>
                        <th>日均成本</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(item, index) in holdingDaysListFull" :key="item.name">
                        <td>
                          <div class="rank-number" :class="{'top-rank': index < 3}">{{ index + 1 }}</div>
                        </td>
                        <td>{{ item.name }}</td>
                        <td>{{ item.days }}天</td>
                        <td>{{ item.purchaseDate }}</td>
                        <td>{{ item.frequency }}</td>
                        <td>{{ item.dailyCost }}元/天</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                
                <div class="holding-days-distribution">
                  <h4>持有天数分布</h4>
                  <div class="holding-days-distribution-chart" ref="holdingDaysDistributionChartRef"></div>
                </div>
              </div>
            </template>
            
            <!-- 物品类别分布详情 -->
            <template v-else-if="currentCardType === 'category-distribution'">
              <div class="detail-section">
                <div class="category-chart-container" ref="categoryDetailChartRef"></div>
                
                <div class="category-stats-grid">
                  <div v-for="category in stats.topCategories" :key="category.name" class="category-stat-card">
                    <div class="category-stat-header" :style="{ backgroundColor: getCategoryColor(category.name) + '22' }">
                      <div class="category-stat-color" :style="{ backgroundColor: getCategoryColor(category.name) }"></div>
                      <div class="category-stat-name">{{ category.name }}</div>
                    </div>
                    <div class="category-stat-body">
                      <div class="category-stat-count">{{ category.count }}件</div>
                      <div class="category-stat-value">总价值: {{ formatCurrency(category.value) }}</div>
                      <div class="category-stat-percent">数量占比: {{ (category.count / stats.totalItems * 100).toFixed(1) }}%</div>
                    </div>
                  </div>
                </div>
                
                <div class="category-trends">
                  <h4>各类别物品增长趋势（近6个月）</h4>
                  <div class="category-trend-chart" ref="categoryTrendChartRef"></div>
                </div>
                
                <div class="category-value-chart">
                  <h4>各类别物品价值对比</h4>
                  <div class="category-value-chart-container" ref="categoryValueChartRef"></div>
                </div>
              </div>
            </template>
            
            <!-- 位置分布详情 -->
            <template v-else-if="currentCardType === 'location-distribution'">
              <div class="detail-section">
                <div class="location-chart-container" ref="locationDetailChartRef"></div>
                
                <div class="location-stats-grid">
                  <!-- 修改 location-stat-card 结构 -->
                  <div v-for="location in stats.topLocations" :key="location.name" class="location-stat-card location-stat-card-alt">
                    <div class="location-stat-alt-header">
                      <div class="location-stat-color" :style="{ backgroundColor: getLocationColor(location.name) }"></div>
                      <div class="location-stat-name">{{ location.name }}</div>
                    </div>
                    <div class="location-stat-body">
                      <div class="location-stat-count">{{ location.count }}件</div>
                      <div class="location-stat-percent">占比: {{ (stats.totalItems > 0 ? (location.count / stats.totalItems * 100) : 0).toFixed(1) }}%</div>
                      <div class="location-stat-space">空间利用率: {{ getSpaceUtilization(location.name) }}%</div>
                    </div>
                  </div>
                </div>
                
                <div class="location-sublocations">
                  <h4>室内空间使用详情</h4>
                  <div class="location-sublocation-chart" ref="sublocationChartRef"></div>
                </div>
                
                <div class="location-optimization">
                  <h4>空间优化建议</h4>
                  <div class="optimization-list">
                    <div class="optimization-item">
                      <div class="optimization-icon">
                        <el-icon><Warning /></el-icon>
                      </div>
                      <div class="optimization-content">
                        <div class="optimization-title">过度拥挤的空间</div>
                        <div class="optimization-desc">厨房储物空间已超过80%利用率，建议考虑整理或重新分配物品</div>
                      </div>
                    </div>
                    <div class="optimization-item">
                      <div class="optimization-icon" style="color: #0071e3">
                        <el-icon><InfoFilled /></el-icon>
                      </div>
                      <div class="optimization-content">
                        <div class="optimization-title">利用率低的空间</div>
                        <div class="optimization-desc">储藏室空间利用率仅为45%，可以考虑转移其他区域的物品</div>
                      </div>
                    </div>
                    <div class="optimization-item">
                      <div class="optimization-icon" style="color: #34c759">
                        <el-icon><Document /></el-icon>
                      </div>
                      <div class="optimization-content">
                        <div class="optimization-title">物品整理建议</div>
                        <div class="optimization-desc">建议整理卧室的衣物，可以释放约15%的储存空间</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
            
            <!-- 月度支出趋势详情 -->
            <template v-else-if="currentCardType === 'monthly-spending'">
              <div class="detail-section">
                <div class="spending-trend-chart" ref="spendingTrendDetailChartRef"></div>
                
                <div class="spending-stats">
                  <div class="stats-card">
                    <div class="stats-card-value">{{ formatCurrency(monthlyAvgSpending) }}</div>
                    <div class="stats-card-label">月均支出</div>
                  </div>
                  <div class="stats-card">
                    <div class="stats-card-value">{{ formatCurrency(highestMonthlySpending) }}</div>
                    <div class="stats-card-label">最高月支出</div>
                  </div>
                  <div class="stats-card">
                    <div class="stats-card-value">{{ formatCurrency(lowestMonthlySpending) }}</div>
                    <div class="stats-card-label">最低月支出</div>
                  </div>
                  <div class="stats-card">
                    <div class="stats-card-value">{{ averageGrowthRate }}%</div>
                    <div class="stats-card-label">平均增长率</div>
                  </div>
                </div>
                
                <div class="spending-table">
                  <h4>月度支出详情</h4>
                  <table>
                    <thead>
                      <tr>
                        <th>月份</th>
                        <th>支出金额</th>
                        <th>环比变化</th>
                        <th>主要花销类别</th>
                        <th>物品数量</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="month in monthlySpendingDetails" :key="month.name">
                        <td>{{ month.name }}</td>
                        <td>{{ formatCurrency(month.amount) }}</td>
                        <td :class="{'text-green': month.change > 0, 'text-red': month.change < 0}">
                          {{ month.change > 0 ? '+' : '' }}{{ month.change }}%
                        </td>
                        <td>{{ month.category }}</td>
                        <td>{{ month.count }}件</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                
                <div class="spending-forecast">
                  <h4>支出预测（未来3个月）</h4>
                  <div class="spending-forecast-chart" ref="spendingForecastChartRef"></div>
                </div>
              </div>
            </template>
            
            <!-- 物品状态分布详情 -->
            <template v-else-if="currentCardType === 'status-distribution'">
              <div class="detail-section">
                <div class="status-chart-container" ref="statusDetailChartRef"></div>
                
                <div class="status-stats-grid">
                  <div v-for="status in stats.itemsByStatus" :key="status.name" class="status-stat-card">
                    <div class="status-stat-header" :class="'status-' + getStatusClass(status.name)">
                      <div class="status-stat-icon">
                        <!-- 修改：使用动态组件渲染图标 -->
                        <el-icon><component :is="getStatusIcon(status.name)" /></el-icon>
                      </div>
                      <div class="status-stat-name">{{ status.name }}</div>
                    </div>
                    <div class="status-stat-body">
                      <div class="status-stat-count">{{ status.count }}件</div>
                      <div class="status-stat-percent">占比: {{ (status.count / stats.totalItems * 100).toFixed(1) }}%</div>
                      <div class="status-stat-actions">查看全部 <el-icon><ArrowRight /></el-icon></div>
                    </div>
                  </div>
                </div>
                
        
              </div>
            </template>
            
            <!-- 默认详情模板（未实现的卡片类型） -->
            <template v-else>
              <div class="detail-placeholder">
                <el-icon><InfoFilled /></el-icon>
                <p>{{ currentCardType }} 的详细数据正在准备中...</p>
              </div>
            </template>
          </div>
          
          <div class="modal-footer">
            <el-button @click="closeModal">关闭</el-button>
            <el-button type="primary" @click="exportCardData">导出数据</el-button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
/* eslint-disable no-unused-vars, no-undef */
import { ref, reactive, onMounted, computed, watchEffect, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useItemsStore } from '../../stores/items'
import { useInventoryStore } from '../../stores/inventory'
import { useStatisticsStore } from '../../stores/statistics'
import { 
  DataLine, Goods, Money, Calendar, Location, 
  ShoppingBag, Box, Document, Histogram, PieChart, TrendCharts, Warning, More, ArrowUp, ArrowDown,
  Close, InfoFilled, ArrowRight
} from '@element-plus/icons-vue'
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { PieChart as EChartsPieChart, BarChart, LineChart, FunnelChart, RadarChart } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { ElMessage } from 'element-plus'

// 显式注册 ECharts 组件和渲染器
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  EChartsPieChart, // 使用别名以避免命名冲突
  BarChart,
  LineChart,
  FunnelChart,
  RadarChart,
  LabelLayout,
  CanvasRenderer
])

// 使用Router
const router = useRouter()

// 使用Stores
const itemsStore = useItemsStore()
const inventoryStore = useInventoryStore()
const statisticsStore = useStatisticsStore()

// 添加对 spendingTrendChartRef 的定义
const spendingTrendChartRef = ref(null)

const loading = ref(false)
const activeTimeRange = ref('all') // 'month', 'quarter', 'year', 'all'
const timeRange = ref('month')
const spendingViewType = ref('monthly')

// 使用频率统计数据
const usageStats = ref([
  { name: '每日', count: 42, color: '#34c759' },
  { name: '每周', count: 68, color: '#007aff' },
  { name: '每月', count: 26, color: '#5856d6' },
  { name: '偶尔', count: 48, color: '#ff9500' },
  { name: '很少', count: 34, color: '#ff3b30' }
])

// 时间范围选项
const timeRangeOptions = [
  { label: '本月', value: 'month' },
  { label: '本季度', value: 'quarter' },
  { label: '今年', value: 'year' },
  { label: '全部', value: 'all' }
]

// 统计数据
const stats = reactive({
            totalItems: 0,
  totalValue: 0,
            newItemsThisMonth: 0,
  totalItemsTrend: 0,
  totalValueTrend: 0,
  topCategories: [],
  topLocations: [],
  monthlySpending: [],
  itemsByStatus: []
})

// 添加状态分布数据的初始化
const statusDistribution = ref({
  loaded: true,
  data: [
    { name: '正常使用', count: 98, percentage: 78.4, color: '#34c759' },
    { name: '需要替换', count: 15, percentage: 12.0, color: '#ff9500' },
    { name: '需要维修', count: 8, percentage: 6.4, color: '#ff3b30' },
    { name: '已停用', count: 4, percentage: 3.2, color: '#a2a2a7' }
  ]
})

// 图表加载状态
const spendingPieChartLoaded = ref(false)
const channelChartLoaded = ref(false)
const categoryChartLoaded = ref(false)
const locationChartLoaded = ref(false)
const spendingTrendChartLoaded = ref(false)
const statusChartLoaded = ref(false)
const usageChartLoaded = ref(false)
const channelFunnelChartLoaded = ref(false)
const ratingChartLoaded = ref(false)


// 获取位置颜色
const locationColors = {
  '客厅': '#007AFF',
  '卧室': '#AF52DE',
  '厨房': '#FF9500',
  '卫生间': '#5AC8FA',
  '储藏室': '#A2845E',
  '书房': '#FF3B30',
  '阳台': '#34C759',
  '其他': '#8E8E93'
}

// 根据类别获取颜色
const getCategoryColor = (category) => {
  return categoryColors[category] || categoryColors['其他']
}

// 格式化金额
const formatCurrency = (value) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2
  }).format(value)
}

// 处理统计卡片操作
const handleStatAction = (stat) => {
  ElMessage.info(`执行操作: ${stat.action}`)
  // 这里可以实现跳转到相应页面或执行相应操作
}

// 概览数据计算属性，保留原始完整数据
const overviewStats = computed(() => {
  // 安全获取即将过期物品数量
  const expiringCount = inventoryStore.getExpiringItems?.length || 0;
  
  // 安全获取已过期物品数量
  const expiredItem = usageStats.value.find(s => s.id === 'expired');
  const expiredCount = expiredItem ? expiredItem.count : 0;
  
  return [
    {
      id: 'total',
      label: '总物品数量',
      value: stats.totalItems,
      icon: Document,
      color: '#0071e3',
      trend: 3
    },
    {
      id: 'value',
      label: '总资产价值',
      value: formatCurrency(stats.totalValue),
      icon: Money,
      color: '#34c759',
      trend: 5
    },
    {
      id: 'new',
      label: '本月新增',
      value: stats.newItemsThisMonth,
      icon: Goods,
      color: '#ff9500',
      trend: 0
    },
    {
      id: 'expiring',
      label: '过期物品',
      value: expiringCount + expiredCount,
      icon: Warning,
      color: '#ff3b30',
      trend: -2
    }
  ]
})

// 过滤后的概览数据，只显示"即将过期"
const filteredOverviewStats = computed(() => {
  return overviewStats.value.filter(stat => stat.id === 'expiring')
})

// 获取统计数据
const fetchStatisticsData = async () => {
  loading.value = true
  try {
    // 引用Dashboard组件的位置ID，从路由中获取
    const dashboardRoute = router.currentRoute.value;
    const query = dashboardRoute.query || {};
    // 获取当前位置ID，优先使用路由参数，如果没有则尝试从Dashboard位置选择器获取
    const currentLocationId = query.locationId || localStorage.getItem('currentLocationId');
    
    // 检查 currentLocationId 是否有效
    if (!currentLocationId || currentLocationId === 'null' || currentLocationId === 'undefined') { 
      console.error('错误：无法获取当前位置ID (locationId missing or invalid)');
      ElMessage.error('无法加载统计数据，请先选择一个位置。');
      loading.value = false; // 停止加载状态
      // 清空现有数据
      clearStatisticsData();
      return; // 提前退出函数，不执行后续API调用
    }
    
    console.log(`获取到当前位置ID: ${currentLocationId}`); // 记录获取到的ID

    // 使用新的API一次性获取该位置的所有物品数据
    const allItems = await itemsStore.fetchAllItems(currentLocationId); // 传递有效的ID
    
    if (!allItems || allItems.length === 0) {
      // 如果获取到的物品为空，提示并清空统计
      console.warn('该位置没有物品数据');
      clearStatisticsData();
      loading.value = false;
      ElMessage.info('当前位置没有物品数据可供统计。');
      return;
    }
    
    console.log(`成功获取到 ${allItems.length} 条物品数据`);
    
    // 使用统计Store进行数据分析
    const analysisSuccess = await statisticsStore.analyzeItems(allItems);
    
    if (!analysisSuccess) {
      throw new Error('统计分析失败');
    }
    
    // 计算统计数据
    stats.totalItems = allItems.length;
    stats.totalValue = calculateTotalValue(allItems);
    stats.newItemsThisMonth = calculateNewItemsThisMonth(allItems);
    stats.totalItemsTrend = calculateItemsTrend(allItems);
    stats.totalValueTrend = calculateValueTrend(allItems);
    
    // 获取分类数据
    stats.topCategories = calculateTopCategories(allItems);
    
    // 获取位置数据
    stats.topLocations = calculateTopLocations(allItems);
    
    // 获取物品状态分布
    stats.itemsByStatus = calculateItemStatusDistribution(allItems);
    
    // 获取月度支出趋势
    stats.monthlySpending = calculateMonthlySpending(allItems);
    
    // 计算花销排行
    spendingRankList.value = calculateSpendingRankList(allItems);
    
    // 从统计Store获取物品花销排行数据
    const storeSpendingRank = statisticsStore.getSpendingRank;
    if (storeSpendingRank && storeSpendingRank.data && storeSpendingRank.data.length > 0) {
      console.log('使用统计Store中的花销排行数据:', storeSpendingRank.data);
      // 转换Store中的数据格式以匹配视图所需格式
      spendingRankList.value = storeSpendingRank.data.map(item => ({
        name: item.name,
        amount: item.value,
        purchaseDate: item.purchaseDate || '未知'
      }));
    }
    
    // 计算持有天数排行
    holdingDaysRankList.value = calculateHoldingDaysRankList(allItems);
    holdingDaysListFull.value = calculateHoldingDaysListFull(allItems);
    
    // 计算购买渠道分布
    channelCategoryList.value = calculateChannelDistribution(allItems);
    
    // 计算使用频率分布
    usageStats.value = calculateUsageFrequency(allItems);
    
    // 计算物品评分数据
    itemRatingData.value = calculateItemRatings(allItems);
    console.log('Item Rating Data:', JSON.stringify(itemRatingData.value)); // 添加日志检查数据
    
    // 计算过期物品
    calculateExpiryItems(allItems);
    
    // 数据加载完成后触发图表渲染
    nextTick(() => { // 确保 DOM 更新后再初始化图表
      initializeDashboardCharts(); // 在数据加载完成后调用
    });
  } catch (error) {
    console.error('获取统计数据失败:', error);
    // 错误处理 - 确保有数据显示
    ElMessage.error('无法加载统计数据: ' + error.message);
    // 保留当前数据或使用备用数据
  } finally {
    loading.value = false;
  }
}

// 处理时间范围变更
const changeTimeRange = (range) => {
  activeTimeRange.value = range
  // 根据时间范围筛选数据
  // 实际项目中这里应该触发新的API请求或重新计算
}

// 新的图表初始化函数
const initializeDashboardCharts = () => {
  // 设置一个短延迟，确保 DOM 元素已经完全渲染
  setTimeout(() => {
    // 渲染饼图
    renderChannelPieChart()
    
    // 使用更长的延迟初始化其他图表
    setTimeout(() => {
      if (spendingPieChartRef.value) renderSpendingPieChart()
      if (categoryChartRef.value) renderCategoryChart()
      if (locationChartRef.value) renderLocationChart()
      if (statusChartRef.value) renderStatusChart()
      if (usageChartRef.value) renderUsageChart()
      if (ratingChartRef.value) renderRatingChart()
    }, 100)
  }, 50)
}

// 监听路由变化，确保每次进入统计页面时都获取最新的位置ID并加载数据
watch(() => router.currentRoute.value.query, (newQuery) => {
  // 如果路由包含位置ID，并且与之前不同，重新加载数据
  if (newQuery && newQuery.locationId) {
    console.log(`路由参数中的位置ID发生变化: ${newQuery.locationId}`);
    fetchStatisticsData();
  }
}, { immediate: true, deep: true });

// 页面加载时获取数据 (不再使用 setTimeout)
onMounted(() => {
  // 确保在组件挂载时加载数据
  fetchStatisticsData();
  
  // 监听窗口大小变化以适应图表尺寸
  window.addEventListener('resize', () => {
    Object.values(charts).forEach(chart => {
      if (chart) {
        chart.resize();
      }
    });
  });
  
  // 监听路由变化，如果需要重新加载数据
  const handleRouteChange = () => {
    // 判断是否需要刷新数据（例如从编辑页面回来）
    if (router.currentRoute.value.meta.refreshStats) {
      fetchStatisticsData();
      }
  };
  
  router.afterEach(handleRouteChange);
  
  return () => {
    window.removeEventListener('resize', () => {});
    router.afterEach(() => {});
  };
});

// 监听加载状态，添加全局加载指示器
watchEffect(() => {
  if (loading.value) {
    document.body.style.cursor = 'progress'
  } else {
    document.body.style.cursor = 'default'
  }
})


// 物品花销分布数据（模拟）
const spendingCategoryList = ref([
  { name: '办公文具', amount: 449.77, percent: 1.27, color: '#4fc3f7' },
  { name: '电子产品', amount: 16707, percent: 47.06, color: '#29b6f6' },
  { name: '电子配件', amount: 568.28, percent: 1.6, color: '#0288d1' },
  { name: '短袖T恤', amount: 546.86, percent: 1.54, color: '#ffb300' },
  { name: '纪念品', amount: 61.13, percent: 0.17, color: '#ff7043' },
  { name: '艺术品', amount: 61.13, percent: 0.17, color: '#ab47bc' },
  { name: '配饰', amount: 949.27, percent: 2.67, color: '#ba68c8' },
  { name: '鞋靴', amount: 1526.26, percent: 4.3, color: '#81c784' },
  { name: '其他', amount: 10937.3, percent: 30.8, color: '#ffd54f' }
])

// 动态计算总花销
const totalSpending = computed(() => {
  const total = spendingCategoryList.value.reduce((sum, item) => sum + item.amount, 0)
  return formatCurrency(total)
})

// 添加：计算纯数字的总花销
const numericTotalSpending = computed(() => {
  // 确保这里使用的源数据是正确的，如果 spendingRankList 代表所有物品，应该用它计算总和
  // 但目前 totalSpending 是基于 spendingCategoryList 计算的，这里保持一致，如果需要修改源数据，需要进一步讨论
  return spendingCategoryList.value.reduce((sum, item) => sum + item.amount, 0);
})

// 物品购买渠道分布数据（模拟）
const channelCategoryList = ref([
  { name: '京东', amount: 6000, percent: 16.9, color: '#1976d2' },
  { name: '淘宝', amount: 7000, percent: 19.7, color: '#ff9800' },
  { name: '拼多多', amount: 3500, percent: 9.9, color: '#e91e63' },
  { name: '线下超市', amount: 8000, percent: 22.5, color: '#43a047' },
  { name: '天猫', amount: 4000, percent: 11.3, color: '#7e57c2' },
  { name: '苏宁', amount: 2000, percent: 5.6, color: '#fbc02d' },
  { name: '其他', amount: 6007, percent: 16.9, color: '#90caf9' }
])

const spendingPieChartRef = ref(null)
const channelPieChartRef = ref(null)


const renderSpendingPieChart = () => {
  if (!spendingPieChartRef.value) return
  try {
    const chart = echarts.init(spendingPieChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        show: false
      },
      series: [
        {
          name: '花销分布',
          type: 'pie',
          radius: ['45%', '70%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          data: spendingCategoryList.map(item => ({
            value: item.amount,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    })
    spendingPieChartLoaded.value = true // 设置加载状态
  } catch (error) {
    console.error('Failed to render spending pie chart:', error)
    spendingPieChartLoaded.value = false
  }
}

const renderChannelPieChart = () => {
  if (!channelPieChartRef.value) {
    console.warn('Channel pie chart DOM element not found');
    channelChartLoaded.value = false;
    return;
  }
  
  // 检查DOM元素尺寸
  if (channelPieChartRef.value.clientWidth === 0 || channelPieChartRef.value.clientHeight === 0) {
    console.warn('Channel pie chart element has no dimensions, delaying initialization');
    setTimeout(() => renderChannelPieChart(), 100); // 延迟100ms重试
    return;
  }
  
  try {
    const chart = echarts.init(channelPieChartRef.value);
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        show: false
      },
      series: [
        {
          name: '渠道分布',
          type: 'pie',
          radius: ['45%', '70%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          data: channelCategoryList.value.map(item => ({
            value: item.amount,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    });
    
    channelChartLoaded.value = true;
    charts.channel = chart;
    
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      if (chart && !chart.isDisposed()) {
        chart.resize();
      }
    });
  } catch (error) {
    console.error('Failed to render channel pie chart:', error);
    channelChartLoaded.value = false;
  }
}


// 物品持有天数排行榜数据（模拟）
const holdingDaysRankList = ref([
  { name: '考试计算器', days: 3735 },
  { name: '黑白配鼠标', days: 2547 },
  { name: '灰色电动吹风', days: 2547 },
  { name: 'U盘', days: 2547 },
  { name: '无线鼠标', days: 2377 }
])

// 物品日均使用成本排行榜数据（模拟）
const dailyCostRankList = [
  { name: '灰色电动吹风', cost: 3.97 },
  { name: 'iPhone 7 32G', cost: 2.97 },
  { name: 'iPhone 11', cost: 3.19 },
  { name: 'iPad', cost: 2.23 },
  { name: '苹果无线快充', cost: 0.97 }
]

// 卡片详情相关
const showModal = ref(false)
const currentCardType = ref('')
const currentCardTitle = ref('')
const currentCardData = ref(null)
const detailLoading = ref(false)
const detailPeriod = ref('month')

// 详情图表引用
const detailSpendingChartRef = ref(null)
const detailDistributionChartRef = ref(null)
const itemsTrendChartRef = ref(null)
const valueTrendChartRef = ref(null)
const newItemsChartRef = ref(null)
const detailUsageChartRef = ref(null)
const detailFunnelChartRef = ref(null)
const detailRatingChartRef = ref(null)

// 卡片类型标题映射
const cardTitles = {
  'total-spending': '物品总花销',
  'spending-distribution': '物品花销分布',
  'channel-distribution': '购买渠道分布',
  'spending-rank': '物品花销排行',
  'holding-days-rank': '持有天数排行',
  'category-distribution': '物品类别分布',
  'location-distribution': '储存位置分布',
  'monthly-spending': '月度支出趋势',
  'status-distribution': '物品状态分布',
  'usage-distribution': '使用频率分布',
  'channel-conversion': '购买渠道转化',
  'item-rating': '物品评分分析',
  'combined-stats': '物品综合统计',
  'overview': '统计概览',
  'usage-summary': '使用频率总览'
}

// 关闭模态框
const closeModal = () => {
  showModal.value = false
}

// 渲染总花销详情图表
const renderDetailSpendingChart = () => {
  if (!detailSpendingChartRef.value) return
  
  const chart = echarts.init(detailSpendingChartRef.value)
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 元'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%', // 为图例留出空间
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: monthlySpendingData.value.map(item => item.month),
      axisLabel: {
        interval: 'auto', // 自动调整间隔
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 元'
      }
    },
    legend: { // 添加图例配置
      data: ['月度支出'],
      bottom: 0,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '月度支出',
        type: 'line', // 修改为 line
        smooth: true, // 使用平滑曲线
        data: monthlySpendingData.value.map(item => item.value),
        lineStyle: { // 设置线条样式
          width: 3,
          color: '#0071e3'
        },
        itemStyle: { // 设置数据点样式
          color: '#0071e3'
        },
        areaStyle: {// 添加面积填充
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
            { offset: 0, color: 'rgba(0, 113, 227, 0.3)' }, // 渐变起始色
              { offset: 1, color: 'rgba(0, 113, 227, 0.05)' } // 渐变结束色
            ]
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        // 确保 data 只包含月度支出数值
        data: monthlySpendingData.value.map(item => item.value)
      }
    ]
  })

  // 窗口大小变化时重绘
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 渲染花销分布详情图表 (添加缺失的函数)
const renderDetailDistributionChart = () => {
  if (!detailDistributionChartRef.value) return
  
  try {
    const chart = echarts.init(detailDistributionChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: spendingCategoryList.value.map(item => item.name)
      },
      series: [
        {
          name: '花销分布',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          data: spendingCategoryList.value.map(item => ({
            value: item.amount,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    })
    
    // 添加窗口大小变化时重绘
    window.addEventListener('resize', () => {
      chart.resize()
    })
  } catch (error) {
    console.error('Failed to render detail distribution chart:', error)
  }
}

// 渲染物品类别分布图
const categoryChartRef = ref(null)
const renderCategoryChart = () => {
  if (!categoryChartRef.value) return
  try {
    const chart = echarts.init(categoryChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '类别分布',
          type: 'pie',
          radius: '70%',
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          data: stats.topCategories.map(item => ({
            value: item.count,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    })
    categoryChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to render category chart:', error)
    categoryChartLoaded.value = false
  }
}

// 渲染位置分布图
const locationChartRef = ref(null)
const renderLocationChart = () => {
  if (!locationChartRef.value) return
  try {
    const chart = echarts.init(locationChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '位置分布',
          type: 'pie',
          radius: '70%',
          center: ['40%', '50%'],
          roseType: 'radius',
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true
            }
          },
          data: stats.topLocations.map(item => ({
            value: item.count,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    })
    charts.location = chart
    locationChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to render location chart:', error)
    locationChartLoaded.value = false
  }
}

// 渲染月度支出趋势图
const spendingChartRef = ref(null)


// 渲染物品状态分布图
const statusChartRef = ref(null)
const renderStatusChart = () => {
  if (!statusChartRef.value) return
  try {
    const chart = echarts.init(statusChartRef.value)
    
    // 状态对应的颜色
    const statusColors = {
      '正常使用': '#34c759',
      '需要替换': '#ff9500',
      '已过期': '#ff3b30',
      '已损坏': '#8e8e93'
    }
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        bottom: '5%',
        left: 'center'
      },
      series: [
        {
          name: '状态分布',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '40%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c}件'
          },
          data: stats.itemsByStatus.map(item => ({
            value: item.count,
            name: item.name,
            itemStyle: { color: statusColors[item.name] || '#8e8e93' }
          }))
        }
      ]
    })
    statusChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to render status chart:', error)
    statusChartLoaded.value = false
  }
}

// 渲染使用频率分布图
const usageChartRef = ref(null)
const renderUsageChart = () => {
  if (!usageChartRef.value) {
    console.error('usageChartRef is not available');
    return;
  }
  
  try {
    const chart = echarts.init(usageChartRef.value)
    
    // 使用频率数据转换
    const usageData = usageStats.value.map(item => ({
      value: item.count,
      name: item.name,
      itemStyle: { color: item.color }
    }))
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal',
        bottom: '5%',
        left: 'center',
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          fontSize: 10
        }
      },
      series: [
        {
          name: '使用频率',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '40%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '12',
              fontWeight: 'bold'
            }
          },
          data: usageData
        }
      ]
    })
    
    // 设置加载状态
    usageChartLoaded.value = true
    
    // 添加窗口大小调整事件
    window.addEventListener('resize', () => {
      chart.resize();
    });
  } catch (error) {
    console.error('Failed to render usage chart:', error)
    usageChartLoaded.value = false
  }
}

// 添加渠道转化数据（模拟）
const channelConversionData = [
  { value: 8000, name: '浏览商品' },
  { value: 6500, name: '加入购物车' },
  { value: 5500, name: '提交订单' },
  { value: 5000, name: '支付完成' },
  { value: 4500, name: '收到物品' }
]

// 渲染购买渠道转化漏斗图
const channelFunnelChartRef = ref(null)
const renderChannelFunnelChart = () => {
  if (!channelFunnelChartRef.value) return
  try {
    const chart = echarts.init(channelFunnelChartRef.value)
    
    const funnelColors = [
      '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'
    ]
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}'
      },
      legend: {
        data: channelConversionData.map(item => item.name),
        bottom: '5%'
      },
      series: [
        {
          name: '渠道转化',
          type: 'funnel',
          left: '10%',
          top: 30,
          bottom: 60,
          width: '80%',
          min: 0,
          max: 10000,
          minSize: '0%',
          maxSize: '100%',
          sort: 'descending',
          gap: 2,
          label: {
            show: true,
            position: 'inside'
          },
          labelLine: {
            length: 10,
            lineStyle: {
              width: 1,
              type: 'solid'
            }
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            label: {
              fontSize: 14
            }
          },
          data: channelConversionData.map((item, index) => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: funnelColors[index % funnelColors.length]
            }
          }))
        }
      ]
    })
    channelFunnelChartLoaded.value = true
  } catch (error) {
    console.error('Failed to render channel funnel chart:', error)
    channelFunnelChartLoaded.value = false
  }
}

// 添加物品评分数据（模拟）
const itemRatingData = ref([
  {
    name: '电子产品',
    value: [4.8, 3.5, 4.2, 5.0, 3.8],
    color: '#007AFF',
    count: 18
  },
  {
    name: '家具',
    value: [3.9, 4.5, 3.2, 4.0, 4.5],
    color: '#A2845E',
    count: 12
  },
  {
    name: '厨房用品',
    value: [4.2, 4.8, 3.8, 3.5, 4.0],
    color: '#FF9500',
    count: 15
  },
  {
    name: '衣物',
    value: [3.5, 4.0, 4.5, 3.8, 4.2],
    color: '#AF52DE',
    count: 22
  },
  {
    name: '工具',
    value: [4.6, 4.8, 3.2, 4.7, 4.1],
    color: '#FF3B30',
    count: 9
  },
  {
    name: '玩具',
    value: [3.8, 3.2, 4.5, 4.0, 4.3],
    color: '#34C759',
    count: 7
  },
  {
    name: '运动',
    value: [4.1, 4.3, 4.0, 4.5, 3.9],
    color: '#5856D6',
    count: 11
  },
  {
    name: '首饰',
    value: [3.2, 4.1, 4.8, 3.5, 4.2],
    color: '#5AC8FA',
    count: 8
  }
])

// 渲染物品评分雷达图
const renderRatingChart = () => { // 修改函数名
  console.log('[renderRatingChart] 开始渲染物品评分雷达图');
  
  if (!ratingChartRef.value) {
    console.error('[renderRatingChart] 错误: ratingChartRef 不存在');
    return;
  }
  
  try {
    console.log('[renderRatingChart] 物品评分数据:', JSON.stringify(itemRatingData.value));
    
    // 检查数据格式是否正确
    if (!itemRatingData.value || !Array.isArray(itemRatingData.value) || itemRatingData.value.length === 0) {
      console.error('[renderRatingChart] 物品评分数据无效或为空');
      return;
    }
    
    // 检查第一项数据的 value 是否是数组
    const firstItem = itemRatingData.value[0];
    if (!firstItem || !Array.isArray(firstItem.value) || firstItem.value.length !== 5) {
      console.error('[renderRatingChart] 物品评分数据格式错误，期望每项有包含5个值的数组:', firstItem);
      return;
    }
    
    // 尝试销毁已有实例
    const existingChart = echarts.getInstanceByDom(ratingChartRef.value);
    if (existingChart) {
      console.log('[renderRatingChart] 销毁已有图表实例');
      existingChart.dispose();
    }
    
    console.log('[renderRatingChart] 初始化新图表实例');
    const chart = echarts.init(ratingChartRef.value);
    
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        bottom: '0%',
        data: itemRatingData.value.map(item => item.name)
      },
      radar: {
        indicator: [
          { name: '性价比', max: 10 },
          { name: '耐用性', max: 10 },
          { name: '外观', max: 10 },
          { name: '实用性', max: 10 },
          { name: '满意度', max: 10 }
        ],
        center: ['50%', '45%'],
        radius: '80%',
        splitNumber: 5,
        shape: 'circle',
        name: {
          textStyle: {
            color: '#666'
          }
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(255, 255, 255, 0.8)'],
            shadowColor: 'rgba(0, 0, 0, 0.05)',
            shadowBlur: 10
          }
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.1)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.1)'
          }
        }
      },
      series: [
        {
          name: '物品评分',
          type: 'radar',
          emphasis: {
            lineStyle: {
              width: 4
            }
          },
          data: itemRatingData.value.map(item => ({
            value: item.value,
            name: item.name,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              type: 'solid',
              width: 2,
              color: item.color
            },
            areaStyle: {
              color: item.color,
              opacity: 0.2
            },
            itemStyle: {
              color: item.color
            }
          }))
        }
      ]
    };
    
    console.log('[renderRatingChart] 设置图表配置');
    chart.setOption(option);
    
    console.log('[renderRatingChart] 图表渲染完成');
    charts.rating = chart;
    ratingChartLoaded.value = true;
    
    // 添加窗口大小调整监听
    window.addEventListener('resize', () => chart.resize());
  } catch (error) {
    console.error('[renderRatingChart] 图表渲染失败:', error);
    ratingChartLoaded.value = false;
  }
}

// 添加辅助函数安全获取已过期物品数量
const getExpiredCount = () => {
  return expiredItems.value.length;
}

// 添加辅助函数
const getTotalItemsFromUsage = () => {
  return usageStats.value.reduce((total, stat) => total + stat.count, 0);
}

// 渲染组合统计图表
const renderCombinedStatsCharts = () => {
  // 物品数量趋势图
  if (itemsTrendChartRef.value) {
    const chart = echarts.init(itemsTrendChartRef.value)
    chart.setOption({
      grid: { top: 10, right: 10, bottom: 10, left: 30 },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月'],
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false },
        splitLine: { show: false }
      },
      series: [{
        data: [110, 112, 121, 124, 126, 128],
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: { width: 3, color: '#0071e3' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(0, 113, 227, 0.3)' },
              { offset: 1, color: 'rgba(0, 113, 227, 0.05)' }
            ]
          }
        }
      }]
    })
  }
  
  // 总资产价值趋势图
  if (valueTrendChartRef.value) {
    const chart = echarts.init(valueTrendChartRef.value)
    chart.setOption({
      grid: { top: 10, right: 10, bottom: 10, left: 30 },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月'],
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false },
        splitLine: { show: false }
      },
      series: [{
        data: [23400, 23900, 24200, 24800, 25300, 25600],
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: { width: 3, color: '#34c759' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(52, 199, 89, 0.3)' },
              { offset: 1, color: 'rgba(52, 199, 89, 0.05)' }
            ]
          }
        }
      }]
    })
  }
  
  // 本月新增物品图
  if (newItemsChartRef.value) {
    const chart = echarts.init(newItemsChartRef.value)
    chart.setOption({
      grid: { top: 5, right: 5, bottom: 5, left: 5 },
      xAxis: {
        type: 'category',
        data: ['1周', '2周', '3周', '4周'],
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { fontSize: 10, color: '#999' }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false },
        splitLine: { show: false }
      },
      series: [{
        data: [3, 4, 2, 3],
        type: 'bar',
        barWidth: '50%',
        itemStyle: {
          color: '#ff9500',
          borderRadius: [3, 3, 0, 0]
        }
      }]
    })
  }
}

// 渲染使用频率详情图表
const renderDetailUsageChart = () => {
  console.log('[renderDetailUsageChart] Entering function'); // 添加日志
  if (!detailUsageChartRef.value) {
    console.error('[renderDetailUsageChart] detailUsageChartRef is not available.'); // 添加错误日志
    return
  }
  console.log('[renderDetailUsageChart] Initializing chart...'); // 添加日志
  
  try { // 添加 try...catch 包裹 ECharts 初始化
    const chart = echarts.init(detailUsageChartRef.value)
    
    // 使用频率数据转换
    const usageData = usageStats.value.map(item => ({
      value: item.count,
      name: item.name,
      itemStyle: { color: item.color }
    }))
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      series: [
        {
          name: '使用频率',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c}件\n({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          data: usageData
        }
      ]
    })
    console.log('[renderDetailUsageChart] Chart initialized successfully.'); // 添加成功日志
  } catch (error) {
    console.error('[renderDetailUsageChart] Error initializing chart:', error); // 捕获并打印错误
  }
}

// 渲染购买渠道转化漏斗详情图表
const renderDetailFunnelChart = () => {
  if (!detailFunnelChartRef.value) return
  
  const chart = echarts.init(detailFunnelChartRef.value)
  
  const funnelColors = [
    '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'
  ]
  
  chart.setOption({
    title: {
      text: '购物流程转化漏斗',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    legend: {
      data: channelConversionData.map(item => item.name),
      bottom: 10
    },
    series: [
      {
        name: '渠道转化',
        type: 'funnel',
        left: '10%',
        top: 60,
        bottom: 60,
        width: '80%',
        min: 0,
        max: 10000,
        minSize: '0%',
        maxSize: '100%',
        sort: 'descending',
        gap: 2,
        label: {
          show: true,
          position: 'inside',
          formatter: '{b}: {c}\n转化率: {d}%'
        },
        labelLine: {
          length: 10,
          lineStyle: {
            width: 1,
            type: 'solid'
          }
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          label: {
            fontSize: 20
          }
        },
        data: channelConversionData.map((item, index) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: funnelColors[index % funnelColors.length]
          }
        }))
      }
    ]
  })
}

// 渲染物品评分雷达详情图表
const renderDetailRatingChart = () => {
  if (!detailRatingChartRef.value) return
  
  const chart = echarts.init(detailRatingChartRef.value)
  
  chart.setOption({
    title: {
      
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: 10,
      data: itemRatingData.value.map(item => item.name)
    },
    radar: {
      indicator: [
        { name: '性价比', max: 10 },
        { name: '耐用性', max: 10 },
        { name: '外观', max: 10 },
        { name: '实用性', max: 10 },
        { name: '满意度', max: 10 }
      ],
      center: ['50%', '50%'],
      radius: '80%',
      splitNumber: 5,
      shape: 'circle',
      name: {
        textStyle: {
          color: '#333',
          fontSize: 14
        }
      },
      splitArea: {
        areaStyle: {
          color: ['rgba(255, 255, 255, 0.8)'],
          shadowColor: 'rgba(0, 0, 0, 0.05)',
          shadowBlur: 10
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.1)'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.1)'
        }
      }
    },
    series: [
      {
        name: '物品评分',
        type: 'radar',
        emphasis: {
          lineStyle: {
            width: 4
          }
        },
        data: itemRatingData.value.map(item => ({
          value: item.value,
          name: item.name,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            type: 'solid',
            width: 2,
            color: item.color
          },
          areaStyle: {
            color: item.color,
            opacity: 0.2
          },
          itemStyle: {
            color: item.color
          }
        }))
      }
    ]
  })
}

// 添加模拟数据和图表引用
const expiryChartRef = ref(null)

// 模拟即将过期物品数据
const expiringItems = ref([
  { name: '牛奶', expiryDate: '2023-12-10', daysLeft: 3 },
  { name: '酸奶', expiryDate: '2023-12-12', daysLeft: 5 },
  { name: '面包', expiryDate: '2023-12-08', daysLeft: 1 },
  { name: '火腿肠', expiryDate: '2023-12-15', daysLeft: 8 }
])

// 模拟已过期物品数据
const expiredItems = ref([
  { name: '鸡蛋', expiryDate: '2023-12-01', daysExpired: 6 },
  { name: '饼干', expiryDate: '2023-11-28', daysExpired: 9 },
  { name: '豆腐', expiryDate: '2023-12-02', daysExpired: 5 },
  { name: '青菜', expiryDate: '2023-12-04', daysExpired: 3 }
])

// 添加渲染过期物品图表的函数
const renderExpiryChart = () => {
  if (!expiryChartRef.value) return
  
  const chart = echarts.init(expiryChartRef.value)
  chart.setOption({
    title: {
      text: '物品过期时间分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}件'
    },
    legend: {
      bottom: '5%',
      left: 'center',
      data: ['已过期', '3天内', '7天内', '15天内', '30天内']
    },
    color: ['#ff3b30', '#ff9500', '#ffcc00', '#34c759', '#5ac8fa'],
    series: [
      {
        name: '过期时间',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}件'
        },
        data: [
          { value: getExpiredCount(), name: '已过期' },
          { value: 3, name: '3天内' },
          { value: 5, name: '7天内' },
          { value: 8, name: '15天内' },
          { value: 12, name: '30天内' }
        ]
      }
    ]
  })
}

// 添加排行榜时间范围选项
const rankTimeRange = ref('all')

// 添加更多模拟数据
const spendingRankList = ref([])  // 清空预设数据，将由实际数据填充

// 购买渠道详情数据
const channelDetails = ref([
  { name: '京东', totalSpending: '¥6,000', avgPrice: '¥300', itemCount: 20, lastPurchase: '2023-11-10' },
  { name: '淘宝', totalSpending: '¥7,000', avgPrice: '¥175', itemCount: 40, lastPurchase: '2023-11-15' },
  { name: '拼多多', totalSpending: '¥3,500', avgPrice: '¥100', itemCount: 35, lastPurchase: '2023-11-18' },
  { name: '线下超市', totalSpending: '¥8,000', avgPrice: '¥400', itemCount: 20, lastPurchase: '2023-11-20' },
  { name: '天猫', totalSpending: '¥4,000', avgPrice: '¥250', itemCount: 16, lastPurchase: '2023-11-12' },
  { name: '苏宁', totalSpending: '¥2,000', avgPrice: '¥285', itemCount: 7, lastPurchase: '2023-10-28' },
  { name: '其他', totalSpending: '¥6,007', avgPrice: '¥240', itemCount: 25, lastPurchase: '2023-11-22' }
])

// 添加图表引用
const channelDetailChartRef = ref(null)
const channelTrendChartRef = ref(null)
const spendingRankChartRef = ref(null)
const spendingCategoryChartRef = ref(null)

// 在showCardDetail函数中添加新图表的渲染调用
const showCardDetail = (type, data = null) => {
  currentCardType.value = type
  currentCardTitle.value = cardTitles[type] || '详情'
  currentCardData.value = data
  showModal.value = true
  detailLoading.value = true

  // 添加日志：检查 spendingRankList 数据
  if (type === 'spending-rank') {
    console.log('[showCardDetail] Data for spending-rank modal:', JSON.stringify(spendingRankList.value));
  }

  // 模拟加载详细数据
  setTimeout(() => {
    detailLoading.value = false
    console.log(`[showCardDetail] detailLoading set to false for type: ${type}`); // 添加日志

    // 等待DOM更新后初始化详情图表
    nextTick(() => {
      console.log(`[showCardDetail] Inside nextTick for type: ${type}`);
      // 延迟执行图表初始化，确保 ref 可用
      setTimeout(() => {
        console.log(`[showCardDetail] Inside setTimeout for type: ${type}`);
        // Log the value before potential chart rendering might interfere
        if (type === 'monthly-spending') {
          console.log('[Debug] monthlySpendingTrend value:', averageGrowthRate.value);
        }
        try {
          // 根据type调用不同的图表初始化函数
          if (type === 'total-spending' && detailSpendingChartRef.value) {
            renderDetailSpendingChart() // 渲染总花销趋势图
            if (detailDistributionChartRef.value) { // 检查 ref 是否存在
              renderDetailDistributionChart() // 同时渲染花销分布饼图
            }
          } else if (type === 'spending-distribution' && detailDistributionChartRef.value) {
            // 此分支不再需要，因为内容已合并
            // renderDetailDistributionChart()
          } else if (type === 'combined-stats') {
            renderCombinedStatsCharts()
          } else if (type === 'usage-distribution' && detailUsageChartRef.value) {
            console.log('[showCardDetail] Calling renderDetailUsageChart');
            renderDetailUsageChart()
          } else if (type === 'channel-conversion' && detailFunnelChartRef.value) {
            renderDetailFunnelChart()
          } else if (type === 'item-rating' && detailRatingChartRef.value) {
            // 添加 try...catch
            try {
              // 尝试先销毁旧实例
              const existingChart = echarts.getInstanceByDom(detailRatingChartRef.value);
              if (existingChart) {
                existingChart.dispose();
              }
              if (detailRatingChartRef.value) renderDetailRatingChart();
            } catch (error) {
              console.error('[showCardDetail] Error rendering item-rating chart:', error);
            }
          } else if (type === 'overview' && data && data.id === 'expiring' && expiryChartRef.value) {
            renderExpiryChart()
          } else if (type === 'channel-distribution') {
            if (channelDetailChartRef.value) renderChannelDetailChart()
            if (channelTrendChartRef.value) renderChannelTrendChart()
            // if (detailFunnelChartRef.value) renderDetailFunnelChart() // 添加漏斗图渲染调用 // 暂时注释掉
          } else if (type === 'spending-rank') {
            // 添加 try...catch
            try {
              if (spendingRankChartRef.value) renderSpendingRankChart();
              if (spendingCategoryChartRef.value) renderSpendingCategoryChart();
            } catch (error) {
              console.error('[showCardDetail] Error rendering spending-rank charts:', error);
            }
          } else if (type === 'holding-days-rank') {
            // 添加 try...catch
            try {
              if (holdingDaysChartRef.value) renderHoldingDaysChart();
              if (holdingDaysDistributionChartRef.value) renderHoldingDaysDistributionChart();
            } catch (error) {
              console.error('[showCardDetail] Error rendering holding-days-rank charts:', error);
            }
          } else if (type === 'category-distribution') {
            if (categoryDetailChartRef.value) renderCategoryDetailChart();
            if (categoryTrendChartRef.value) renderCategoryTrendChart();
            if (categoryValueChartRef.value) renderCategoryValueChart();
          } else if (type === 'location-distribution') { 
            // 增加位置分布详情图表的延迟渲染时间
            setTimeout(() => {
              if (locationDetailChartRef.value) {
                console.log('[showCardDetail] Calling initLocationDetailChart for location-distribution');
                initLocationDetailChart()
              } else {
                console.error('[showCardDetail] locationDetailChartRef not available for location-distribution');
              }
            }, 300);
          } else if (type === 'monthly-spending') { 
            // 增加月度支出趋势图表的延迟渲染时间
            setTimeout(() => {
              if (spendingTrendDetailChartRef.value) {
                  initSpendingTrendDetailChart()
              } else {
                  console.error('[showCardDetail] spendingTrendDetailChartRef not available for monthly-spending');
              }
              if (spendingForecastChartRef.value) {
                  initSpendingForecastChart()
              } else {
                  console.error('[showCardDetail] spendingForecastChartRef not available for monthly-spending');
              }
            }, 300);
          } else if (type === 'status-distribution') {
            // 增加物品状态分布图表的延迟渲染时间
            setTimeout(() => {
              if (statusDetailChartRef.value) {
                initStatusDetailChart()
              } else {
                console.error('[showCardDetail] statusDetailChartRef not available for status-distribution');
              }
            }, 300);
          }
          // 如果是因为 ref 还没准备好导致图表没渲染，检查一下
          if (type === 'usage-distribution' && !detailUsageChartRef.value) {
             console.error('[showCardDetail] detailUsageChartRef still not available after setTimeout(0)');
          }
        } catch (error) {
          console.error('Error initializing detail chart:', error) // 检查是否有错误输出
        }
      }, 100); // 增加延迟时间
    })
  }, 800)
}

// 添加购买渠道分布图表渲染函数
const renderChannelDetailChart = () => {
  console.log('[renderChannelDetailChart] Function called.'); // 添加日志：函数入口
  if (!channelDetailChartRef.value) {
    console.error('[renderChannelDetailChart] channelDetailChartRef is not available.'); // 添加日志：Ref 不可用
    return
  }
  console.log('[renderChannelDetailChart] Initializing chart for element:', channelDetailChartRef.value); // 添加日志：Ref 元素

  try { // 添加 try...catch
    const chart = echarts.init(channelDetailChartRef.value)
    console.log('[renderChannelDetailChart] ECharts instance created.'); // 添加日志：实例创建

    const options = { // 将配置提取出来方便打印
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: channelCategoryList.value.map(item => item.name) // 确保使用 .value
      },
      series: [
        {
          name: '渠道分布',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: channelCategoryList.value.map(item => ({ // 确保使用 .value
            value: item.amount,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    };
    // console.log('[renderChannelDetailChart] Setting options:', JSON.stringify(options)); // 暂时注释掉，避免日志过长

    chart.setOption(options)
    console.log('[renderChannelDetailChart] Chart options set successfully.'); // 添加日志：设置成功

    // 添加窗口大小变化监听器
    window.addEventListener('resize', () => {
      chart.resize();
    });

  } catch (error) {
    console.error('[renderChannelDetailChart] Error during chart initialization or setting options:', error); // 添加日志：捕获错误
  }
}

// 添加渠道花销趋势图表渲染函数
const renderChannelTrendChart = () => {
  if (!channelTrendChartRef.value) return
  
  const chart = echarts.init(channelTrendChartRef.value)
  
  // 模拟6个月的数据
  const months = ['6月', '7月', '8月', '9月', '10月', '11月']
  const channelData = {
    '京东': [580, 620, 650, 590, 610, 600],
    '淘宝': [650, 680, 670, 710, 720, 700],
    '拼多多': [290, 320, 350, 370, 390, 350],
    '线下超市': [750, 780, 800, 820, 780, 800],
    '天猫': [380, 350, 390, 420, 380, 370],
    '其他': [550, 570, 530, 590, 610, 580]
  }
  
  const series = Object.keys(channelData).map(channel => {
    const color = channelCategoryList.find(item => item.name === channel)?.color || '#5470c6'
    return {
      name: channel,
      type: 'line',
      smooth: true,
      emphasis: {
        focus: 'series'
      },
      lineStyle: {
        width: 3,
        color: color
      },
      data: channelData[channel]
    }
  })
  
  chart.setOption({
    title: {
      text: '各渠道花销趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: Object.keys(channelData),
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}元'
      }
    },
    series: series
  })
}

// 添加物品花销排行图表渲染函数
const renderSpendingRankChart = () => {
  if (!spendingRankChartRef.value) return
  
  // 确保spendingRankList有数据
  if (!spendingRankList.value || spendingRankList.value.length === 0) {
    console.warn('花销排行数据为空，无法渲染图表');
    return;
  }

  const chart = echarts.init(spendingRankChartRef.value)

  // 准备数据
  const chartData = [...spendingRankList.value]
    .slice(0, 10) // 取前10个
    .sort((a, b) => a.amount - b.amount) // 从小到大排序，用于水平条形图
  
  chart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
      },
      formatter: function(params) {
        return `${params[0].name}: ${formatCurrency(params[0].value)}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLabel: {
        formatter: function(value) {
          return '¥' + value
        }
        }
      },
      yAxis: {
        type: 'category',
      data: chartData.map(item => item.name),
      axisTick: {
        alignWithLabel: true
        }
      },
      series: [
        {
          name: '花销金额',
          type: 'bar',
        barWidth: '60%',
        data: chartData.map(item => ({
          value: item.amount,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#0a6ecd' }
            ])
          }
        })),
          label: {
            show: true,
            position: 'right',
          formatter: '{c}'
          }
        }
      ]
  })
}

// 添加高花销物品类别分布图表渲染函数
const renderSpendingCategoryChart = () => {
  if (!spendingCategoryChartRef.value) return
  
  const chart = echarts.init(spendingCategoryChartRef.value)
  
  // 模拟高花销物品类别分布数据
  const categoryData = [
    { name: '电子产品', value: 16500, color: '#0EA5E9' },
    { name: '家具', value: 6500, color: '#A78BFA' },
    { name: '服饰', value: 4800, color: '#EC4899' },
    { name: '厨房用品', value: 3200, color: '#10B981' },
    { name: '其他', value: 4500, color: '#8E8E93' }
  ]
  
  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}元 ({d}%)'
    },
    legend: {
      bottom: 0,
      left: 'center'
    },
    series: [
      {
        name: '类别花销',
        type: 'pie',
        radius: '55%',
        center: ['50%', '45%'],
        data: categoryData.map(item => ({
          value: item.value,
          name: item.name,
          itemStyle: { color: item.color }
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

// 监听排行榜时间范围变化
watch(rankTimeRange, (newValue) => {
  nextTick(() => {
    if (spendingRankChartRef.value) {
      renderSpendingRankChart()
    }
  })
})

// 添加持有天数排行榜完整数据
const holdingDaysListFull = ref([
  { name: '考试计算器', days: 3735, purchaseDate: '2013-05-10', frequency: '偶尔', dailyCost: 0.56 },
  { name: '黑白配鼠标', days: 2547, purchaseDate: '2016-08-22', frequency: '频繁', dailyCost: 0.39 },
  { name: '灰色电动吹风', days: 2547, purchaseDate: '2016-08-22', frequency: '经常', dailyCost: 0.31 },
  { name: 'U盘', days: 2547, purchaseDate: '2016-08-22', frequency: '频繁', dailyCost: 0.12 },
  { name: '无线鼠标', days: 2377, purchaseDate: '2017-02-08', frequency: '频繁', dailyCost: 0.29 },
  { name: '机械键盘', days: 1925, purchaseDate: '2018-05-12', frequency: '频繁', dailyCost: 0.42 },
  { name: '耳机', days: 1850, purchaseDate: '2018-07-25', frequency: '频繁', dailyCost: 0.27 },
  { name: '床头台灯', days: 1679, purchaseDate: '2019-01-12', frequency: '经常', dailyCost: 0.18 },
  { name: '电饭煲', days: 1462, purchaseDate: '2019-08-18', frequency: '经常', dailyCost: 0.34 },
  { name: '电热水壶', days: 1370, purchaseDate: '2019-11-18', frequency: '经常', dailyCost: 0.22 }
])

// 添加统计数据
const averageHoldingDays = 876
const longestHoldingDays = 3735
const shortestHoldingDays = 15
const recentlyAddedItems = 12

// 添加新的图表引用
const holdingDaysChartRef = ref(null)
const holdingDaysDistributionChartRef = ref(null)
const categoryDetailChartRef = ref(null)
const categoryTrendChartRef = ref(null)
const categoryValueChartRef = ref(null)

// 持有天数排行图表渲染函数
const renderHoldingDaysChart = () => {
  if (!holdingDaysChartRef.value) return
  
  const chart = echarts.init(holdingDaysChartRef.value)
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}天'
      }
    },
    yAxis: {
      type: 'category',
      // 使用 .value
      data: holdingDaysListFull.value.slice(0, 10).map(item => item.name).reverse(),
      axisLabel: {
        width: 60,
        overflow: 'truncate'
      }
    },
    series: [
      {
        name: '持有天数',
        type: 'bar',
        // 使用 .value
        data: holdingDaysListFull.value.slice(0, 10).map(item => item.days).reverse(),
        itemStyle: {
          color: function(params) {
            const colors = ['#10B981', '#0EA5E9', '#8B5CF6', '#EC4899', '#F59E0B', '#8E8E93', '#64748B', '#6D28D9', '#059669', '#0369A1']
            return colors[params.dataIndex % colors.length]
          },
          borderRadius: [0, 4, 4, 0]
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}天'
        }
      }
    ]
  })
}

// 持有天数分布图表渲染函数
const renderHoldingDaysDistributionChart = () => {
  if (!holdingDaysDistributionChartRef.value) return
  
  const chart = echarts.init(holdingDaysDistributionChartRef.value)
  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}件'
    },
    legend: {
      bottom: 0,
      left: 'center'
    },
    series: [
      {
        name: '持有天数',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}件'
        },
        data: [
          { value: 24, name: '30天内', itemStyle: { color: '#10B981' } },
          { value: 42, name: '1-3个月', itemStyle: { color: '#0EA5E9' } },
          { value: 38, name: '3-6个月', itemStyle: { color: '#8B5CF6' } },
          { value: 57, name: '6-12个月', itemStyle: { color: '#EC4899' } },
          { value: 89, name: '1-3年', itemStyle: { color: '#F59E0B' } },
          { value: 42, name: '3年以上', itemStyle: { color: '#8E8E93' } }
        ]
      }
    ]
  })
}

// 物品类别分布详情图表渲染函数
const renderCategoryDetailChart = () => {
  if (!categoryDetailChartRef.value) return
  
  const chart = echarts.init(categoryDetailChartRef.value)
  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}件 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    series: [
      {
        name: '类别分布',
        type: 'pie',
        radius: ['30%', '60%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}件\n({d}%)'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: stats.topCategories.map(item => ({
          value: item.count,
          name: item.name,
          itemStyle: { color: item.color }
        }))
      }
    ]
  })
}

// 类别物品增长趋势图表渲染函数
const renderCategoryTrendChart = () => {
  if (!categoryTrendChartRef.value) return
  
  const chart = echarts.init(categoryTrendChartRef.value)
  
  // 模拟6个月的数据
  const months = ['6月', '7月', '8月', '9月', '10月', '11月']
  const categoryTrendData = {
    '电子产品': [28, 29, 30, 31, 32, 32],
    '家具': [22, 22, 23, 23, 24, 24],
    '厨房用品': [15, 16, 16, 17, 18, 18],
    '食品': [12, 13, 14, 14, 15, 15],
    '衣物': [10, 10, 11, 11, 12, 12],
    '其他': [15, 15, 16, 16, 17, 17]
  }
  
  // 颜色映射
  const categoryColors = {
    '电子产品': '#007aff',
    '家具': '#ff9500',
    '厨房用品': '#34c759',
    '食品': '#5e5ce6',
    '衣物': '#ff3b30',
    '其他': '#a2a2a7'
  }
  
  const series = Object.keys(categoryTrendData).map(category => {
    return {
      name: category,
      type: 'line',
      smooth: true,
      emphasis: {
        focus: 'series'
      },
      lineStyle: {
        width: 3,
        color: categoryColors[category] || '#a2a2a7'
      },
      data: categoryTrendData[category]
    }
  })
  
  chart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: Object.keys(categoryTrendData),
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}件'
      }
    },
    series: series
  })
}

// 类别物品价值对比图表渲染函数
const renderCategoryValueChart = () => {
  if (!categoryValueChartRef.value) return
  
  const chart = echarts.init(categoryValueChartRef.value)
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['总价值', '平均单价'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: stats.topCategories.map(item => item.name)
    },
    yAxis: [
      {
        type: 'value',
        name: '总价值',
        axisLabel: {
          formatter: '{value}元'
        }
      },
      {
        type: 'value',
        name: '平均单价',
        axisLabel: {
          formatter: '{value}元'
        }
      }
    ],
    series: [
      {
        name: '总价值',
        type: 'bar',
        data: stats.topCategories.map(item => item.value),
        itemStyle: {
          color: function(params) {
            return stats.topCategories[params.dataIndex].color
          }
        }
      },
      {
        name: '平均单价',
        type: 'line',
        yAxisIndex: 1,
        data: stats.topCategories.map(item => (item.value / item.count).toFixed(0)),
        lineStyle: {
          width: 3,
          color: '#0071e3'
        },
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#0071e3'
        }
      }
    ]
  })
}

// 状态分布相关
const statusDetailChartRef = ref(null)
const statusTrendChartRef = ref(null)

// 位置分布相关
const locationDetailChartRef = ref(null)
const sublocationChartRef = ref(null)

// 月度支出相关
const spendingTrendDetailChartRef = ref(null)
const spendingForecastChartRef = ref(null)
const spendingPeriod = ref('month')
const monthlyAvgSpending = ref(1250)
const highestMonthlySpending = ref(2300)
const lowestMonthlySpending = ref(800)
const monthlySpendingDetails = ref([
  { name: '2023-12', amount: 1500, change: -5, category: '厨房用品', count: 8 },
  { name: '2023-11', amount: 1850, change: 12, category: '电子产品', count: 3 },
  { name: '2023-10', amount: 1450, change: -8, category: '办公用品', count: 5 },
  { name: '2023-09', amount: 2100, change: 15, category: '家居家具', count: 4 },
  { name: '2023-08', amount: 1750, change: 0, category: '生活用品', count: 6 }
])

// 月度支出数据初始化
const monthlySpendingData = ref([
  { month: '1月', value: 4500 },
  { month: '2月', value: 3200 },
  { month: '3月', value: 5800 },
  { month: '4月', value: 2900 },
  { month: '5月', value: 4100 },
  { month: '6月', value: 6200 },
  { month: '7月', value: 3700 },
  { month: '8月', value: 4900 },
  { month: '9月', value: 5300 },
  { month: '10月', value: 4700 },
  { month: '11月', value: 7200 },
  { month: '12月', value: 8500 }
])

// 计算最大月度支出用于比例计算
const maxMonthlySpending = computed(() => {
  return Math.max(...monthlySpendingData.value.map(item => item.value))
})

// 工具函数
const getLocationColor = (location) => {
  const colorMap = {
    '客厅': '#FF6B6B',
    '卧室': '#4ECDC4',
    '厨房': '#FFD166',
    '卫生间': '#6A0572',
    '书房': '#1A535C',
    '储藏室': '#7B68EE'
  }
  return colorMap[location] || '#909399'
}

const getSpaceUtilization = (location) => {
  const utilizationMap = {
    '客厅': 65,
    '卧室': 75,
    '厨房': 85,
    '卫生间': 60,
    '书房': 55,
    '储藏室': 45
  }
  return utilizationMap[location] || 50
}

const getStatusClass = (status) => {
  const statusClassMap = {
    '正常使用': 'normal',
    '闲置': 'idle',
    '损坏': 'damaged',
    '借出': 'lent',
    '即将过期': 'expiring'
  }
  return statusClassMap[status] || 'normal'
}

const getStatusIcon = (status) => {
  const statusIconMap = {
    '正常使用': 'Check',
    '闲置': 'Timer',
    '损坏': 'Warning',
    '借出': 'Share',
    '即将过期': 'Clock'
  }
  return statusIconMap[status] || 'More'
}

const getStatusType = (status) => {
  const statusTypeMap = {
    '正常使用': 'success',
    '闲置': 'info',
    '损坏': 'danger',
    '借出': 'warning',
    '即将过期': 'warning'
  }
  return statusTypeMap[status] || 'info'
}

// 图表初始化函数
const initStatusDetailChart = () => {
  if (!statusDetailChartRef.value) {
    console.error('statusDetailChartRef 元素不存在');
    return;
  }
  
  // 确保容器有大小并且可见
  if (statusDetailChartRef.value.clientWidth === 0 || statusDetailChartRef.value.clientHeight === 0) {
    console.warn('statusDetailChartRef 元素宽度或高度为 0，添加定时器延迟初始化');
    setTimeout(() => initStatusDetailChart(), 200);
    return;
  }
  
  try {
    const chart = echarts.init(statusDetailChartRef.value);
    
    // 安全获取数据，如果 stats.itemsByStatus 存在则使用它，否则使用空数组或 statusDistribution 数据
    const statusData = stats.itemsByStatus || statusDistribution.value.data || [];
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: statusData.map(item => item.name || item.status)
      },
      series: [
        {
          name: '物品状态',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: statusData.map(item => ({
            value: item.count,
            name: item.name || item.status,
            itemStyle: { 
              // 使用状态色彩映射
              color: item.color || {
                '正常使用': '#34c759',
                '需要替换': '#ff9500',
                '已过期': '#ff3b30',
                '已损坏': '#8e8e93'
              }[item.name || item.status] || '#8e8e93'
            }
          }))
        }
      ]
    };
    
    chart.setOption(option);
    
    window.addEventListener('resize', () => {
      chart.resize();
    });
    
    console.log('statusDetailChart 初始化成功');
  } catch (error) {
    console.error('初始化 statusDetailChart 时出错:', error);
  }
}

const initLocationDetailChart = () => {
  if (!locationDetailChartRef.value) {
    console.error('locationDetailChartRef 元素不存在');
    return;
  }
  
  // 确保容器有大小并且可见
  if (locationDetailChartRef.value.clientWidth === 0 || locationDetailChartRef.value.clientHeight === 0) {
    console.warn('locationDetailChartRef 元素宽度或高度为 0，添加定时器延迟初始化');
    setTimeout(() => initLocationDetailChart(), 200);
    return;
  }
  
  try {
    const chart = echarts.init(locationDetailChartRef.value);
    
    // 安全获取数据
    const locationData = stats.topLocations || [];
    if (!locationData || !locationData.length) {
      console.warn('位置分布数据为空');
      return;
    }
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}件 ({d}%)' // Adjusted formatter for clarity
      },
      legend: {
        orient: 'vertical',
        right: 10, // Changed from left to right
        top: 'center', // Align legend to the center vertically
        data: locationData.map(item => item.name) // Correct data source
      },
      series: [
        {
          name: '位置分布',
          type: 'pie',
          radius: '70%', // Slightly larger radius
          center: ['40%', '50%'], // Adjust center for legend on the right
          data: locationData.map(item => ({ // Correct data source and property name
            value: item.count,
            name: item.name, // Use 'name' instead of 'location'
            itemStyle: {
              color: item.color // 直接使用数据项的color属性
            }
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    
    chart.setOption(option);
    window.addEventListener('resize', () => {
      chart.resize();
    });
    
    console.log('Location chart initialized successfully');
  } catch (error) {
    console.error('Failed to initialize location chart:', error);
  }
}

const initSpendingTrendDetailChart = () => {
  if (!spendingTrendDetailChartRef.value) return
  
  const chart = echarts.init(spendingTrendDetailChartRef.value)
  const months = monthlySpendingDetails.value.map(item => item.name)
  const amounts = monthlySpendingDetails.value.map(item => item.amount)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}元'
    },
    xAxis: {
      type: 'category',
      data: months
    },
    yAxis: {
      type: 'value',
      name: '金额 (元)'
    },
    series: [
      {
        data: amounts,
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          shadowColor: 'rgba(0,0,0,0.3)',
          shadowBlur: 10,
          shadowOffsetY: 8
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
      }
    ]
  }
  
  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initSpendingForecastChart = () => {
  if (!spendingForecastChartRef.value) return
  
  const chart = echarts.init(spendingForecastChartRef.value)
  // 模拟预测数据
  const months = ['06', '07', '08']
  const forecastData = [1400, 1550, 1650]
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}元 (预测)'
    },
    xAxis: {
      type: 'category',
      data: months.map(m => `2024-${m}`)
    },
    yAxis: {
      type: 'value',
      name: '预测金额 (元)'
    },
    series: [
      {
        data: forecastData,
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 2,
          type: 'dashed'
        },
        itemStyle: {
          color: '#8e44ad'
        }
      }
    ]
  }
  
  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 数据导出功能
const exportCardData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage({
      message: '数据已导出到您的下载文件夹',
      type: 'success'
    })
  }, 1500)
}

// 确保在组件挂载后初始化所有图表
onMounted(() => {
  fetchStatisticsData()
  
  // 延迟执行以确保DOM元素已完全渲染
  nextTick(() => {
    // 初始化所有卡片中的图表
    initializeDashboardCharts()
  })
})



// 更新图表初始化函数，确保处理不存在的DOM元素情况
const initSpendingPieChart = () => {
  if (!spendingPieChartRef.value) {
    console.warn('Spending pie chart DOM element not found')
    spendingPieChartLoaded.value = false // 未找到元素，设置未加载
    return
  }
  
  try {
    const chart = echarts.init(spendingPieChartRef.value)
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      series: [
        {
          type: 'pie',
          radius: '70%',
          center: ['50%', '50%'],
          data: spendingCategoryList.value.map(item => ({
            value: item.amount,
            name: item.name,
            itemStyle: { color: item.color }
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          labelLine: {
            show: false
          },
          label: {
            show: false
          }
        }
      ]
    })
    
    // 保存图表实例以便于后续可能的更新/销毁
    charts.spendingPie = chart
    spendingPieChartLoaded.value = true // 加载成功
    
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize spending pie chart:', error)
    spendingPieChartLoaded.value = false // 加载失败
  }
}

// 同样更新其他图表初始化函数
const initChannelChart = () => {
  if (!channelPieChartRef.value) {
    console.warn('Channel pie chart DOM element not found')
    channelChartLoaded.value = false
    return
  }
  
  try {
    const chart = echarts.init(channelPieChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      series: [
        {
          name: '渠道分布', 
          type: 'pie',
          radius: '70%',
          center: ['50%', '50%'],
          data: channelCategoryList.value.map(item => ({
            value: item.amount,
            name: item.name,
            itemStyle: { color: item.color }
          })),
          label: {
            show: false
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
    
    charts.channel = chart
    channelChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize channel chart:', error)
    channelChartLoaded.value = false
  }
}

const initUsageChart = () => {
  if (!usageChartRef.value) {
    console.warn('Usage chart DOM element not found')
    usageChartLoaded.value = false
    return
  }
  try {
    const chart = echarts.init(usageChartRef.value)
    
    // 确保使用带颜色的数据
    const usageData = usageStats.value.map(item => ({
      value: item.count,
      name: item.name,
      itemStyle: { color: item.color }
    }))
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        type: 'scroll',
        bottom: '5%',
        left: 'center',
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '使用频率',
          type: 'pie',
          radius: ['50%', '70%'],
          center: ['50%', '40%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          data: usageData
        }
      ]
    })
    
    charts.usage = chart
    usageChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize usage chart:', error)
    usageChartLoaded.value = false
  }
}

const initCategoryChart = () => {
  if (!categoryChartRef.value) {
    console.warn('Category chart DOM element not found')
    categoryChartLoaded.value = false
    return
  }
  // 添加尺寸检查和延迟
  if (categoryChartRef.value.clientWidth === 0 || categoryChartRef.value.clientHeight === 0) {
    console.warn('Category chart element has no dimensions, delaying initialization.');
    setTimeout(() => initCategoryChart(), 100); // 延迟100ms重试
    return;
  }

  try {
    const chart = echarts.init(categoryChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '类别分布',
          type: 'pie',
          radius: '70%',
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          data: stats.topCategories.map(item => ({
            value: item.count,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    })
    charts.category = chart
    categoryChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize category chart:', error)
    categoryChartLoaded.value = false
  }
}

const initLocationChart = () => {
  if (!locationChartRef.value) {
    console.warn('Location chart DOM element not found')
    locationChartLoaded.value = false
    return
  }
  // 添加尺寸检查和延迟
  if (locationChartRef.value.clientWidth === 0 || locationChartRef.value.clientHeight === 0) {
    console.warn('Location chart element has no dimensions, delaying initialization.');
    setTimeout(() => initLocationChart(), 100); // 延迟100ms重试
    return;
  }

  try {
    const chart = echarts.init(locationChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '位置分布',
          type: 'pie',
          radius: '70%',
          center: ['40%', '50%'],
          roseType: 'radius',
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true
            }
          },
          data: stats.topLocations.map(item => ({
            value: item.count,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    })
    charts.location = chart
    locationChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize location chart:', error)
    locationChartLoaded.value = false
  }
}

const initStatusChart = () => {
  if (!statusChartRef.value) {
    console.warn('Status chart DOM element not found')
    statusChartLoaded.value = false
    return
  }
  try {
    const chart = echarts.init(statusChartRef.value)
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}件 ({d}%)'
      },
      legend: {
        bottom: '5%',
        left: 'center'
      },
      series: [
        {
          name: '状态分布',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '40%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c}件'
          },
          data: stats.itemsByStatus.map(item => ({
            value: item.count,
            name: item.name,
            itemStyle: { color: item.color }
          }))
        }
      ]
    })
    charts.status = chart
    statusChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize status chart:', error)
    statusChartLoaded.value = false
  }
}

const initRatingChart = () => {
  if (!ratingChartRef.value) {
    console.warn('Rating chart DOM element not found')
    ratingChartLoaded.value = false
    return
  }
  try {
    const chart = echarts.init(ratingChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        bottom: '0%',
        data: itemRatingData.value.map(item => item.name)
      },
      radar: {
        indicator: [
          { name: '性价比', max: 5 },
          { name: '耐用性', max: 5 },
          { name: '外观', max: 5 },
          { name: '实用性', max: 5 },
          { name: '满意度', max: 5 }
        ],
        center: ['50%', '45%'],
        radius: '60%',
        splitNumber: 5,
        shape: 'circle',
        name: {
          textStyle: {
            color: '#666'
          }
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(255, 255, 255, 0.8)'],
            shadowColor: 'rgba(0, 0, 0, 0.05)',
            shadowBlur: 10
          }
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.1)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.1)'
          }
        }
      },
      series: [
        {
          name: '物品评分',
          type: 'radar',
          emphasis: {
            lineStyle: {
              width: 4
            }
          },
          data: itemRatingData.value.map(item => ({
            value: item.value,
            name: item.name,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              type: 'solid',
              width: 2,
              color: item.color
            },
            areaStyle: {
              color: item.color,
              opacity: 0.2
            },
            itemStyle: {
              color: item.color
            }
          }))
        }
      ]
    })
    charts.rating = chart
    ratingChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize rating chart:', error)
    ratingChartLoaded.value = false
  }
}

const initSpendingTrendChart = () => {
  if (!spendingTrendChartRef.value) {
    console.warn('Spending trend chart DOM element not found')
    spendingTrendChartLoaded.value = false
    return
  }
  try {
    const chart = echarts.init(spendingTrendChartRef.value)
    chart.setOption({
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c} 元'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: stats.monthlySpending.map(item => item.month),
        axisLabel: {
          interval: 1,
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      series: [{
          data: stats.monthlySpending.map(item => item.value),
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#0071e3'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(0, 113, 227, 0.3)' },
              { offset: 1, color: 'rgba(0, 113, 227, 0.05)' }
            ]
          }
          },
            itemStyle: {
          color: '#0071e3'
          }
      }]
    })
    charts.spendingTrend = chart
    spendingTrendChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize spending trend chart:', error)
    spendingTrendChartLoaded.value = false
  }
}

const initChannelFunnelChart = () => {
  if (!channelFunnelChartRef.value) {
    console.warn('Channel funnel chart DOM element not found')
    channelFunnelChartLoaded.value = false
    return
  }
  
  try {
    const chart = echarts.init(channelFunnelChartRef.value)
    
    // 准备数据 - 这里使用了模拟数据
    const funnelData = [
      { value: 80, name: '浏览商品' },
      { value: 60, name: '加入购物车' },
      { value: 45, name: '提交订单' },
      { value: 40, name: '支付完成' },
      { value: 30, name: '收到物品' }
    ]
    
    // 准备颜色
    const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
    
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}'
      },
      legend: {
        data: funnelData.map(item => item.name),
        bottom: '5%'
      },
      series: [
        {
          name: '渠道转化',
          type: 'funnel',
          left: '10%',
          top: 30,
          bottom: 60,
          width: '80%',
          min: 0,
          max: 100,
          minSize: '0%',
          maxSize: '100%',
          sort: 'descending',
          gap: 2,
          label: {
            show: true,
            position: 'inside'
          },
          labelLine: {
            length: 10,
            lineStyle: {
              width: 1,
              type: 'solid'
            }
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            label: {
              fontSize: 14
            }
          },
          data: funnelData.map((item, index) => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: funnelColors[index % funnelColors.length]
            }
          }))
        }
      ]
    })
    charts.channelFunnel = chart
    channelFunnelChartLoaded.value = true
    window.addEventListener('resize', () => chart.resize())
  } catch (error) {
    console.error('Failed to initialize channel funnel chart:', error)
    channelFunnelChartLoaded.value = false
  }
}



// 添加存储图表实例的对象，方便管理
const charts = reactive({
  spendingPie: null,
  channel: null,
  usage: null,
  category: null,
  location: null,
  status: null,
  rating: null,
  spendingTrend: null,
  channelFunnel: null,
  // 详情图表实例 (如果需要管理)
  detailSpending: null,
  detailDistribution: null,
  itemsTrend: null,
  valueTrend: null,
  newItems: null,
  detailUsage: null,
  detailFunnel: null,
  detailRating: null,
  expiry: null,
  channelDetail: null,
  channelTrend: null,
  spendingRank: null,
  spendingCategory: null,
  holdingDays: null,
  holdingDaysDistribution: null,
  categoryDetail: null,
  categoryTrend: null,
  categoryValue: null,
  locationDetail: null,
  sublocation: null,
  spendingTrendDetail: null,
  spendingForecast: null,
  statusDetail: null,
  statusTrend: null,
})

// 获取物品类别颜色
const categoryColors = {
  '电子产品': '#007AFF',
  '家具': '#A2845E',
  '食品': '#34C759',
  '衣物': '#AF52DE',
  '厨房用品': '#FF9500',
  '日用品': '#5AC8FA',
  '药品': '#FF2D55',
  '书籍': '#FF3B30',
  '其他': '#8E8E93'
}

// 获取所有的模拟数据 (确保这些存在)
const usageFrequencyDistribution = computed(() => statisticsStore.getUsageFrequencyDistribution)
const itemRatingAnalysis = computed(() => statisticsStore.getItemRatingAnalysis)
const monthlySpendingTrend = computed(() => statisticsStore.getMonthlySpendingTrend)

// 获取月份颜色
function getMonthColor(index) {
  const colors = [
    '#007aff', '#34c759', '#5e5ce6', '#ff9500', '#ff3b30',
    '#64d2ff', '#30d158', '#6e6ef0', '#ffa620', '#ff453a',
    '#00b8ff', '#2ed158', '#7373f5', '#ffb340', '#ff5147'
  ]
  return colors[index % colors.length]
}

// 获取评分颜色
function getRatingColor(rating) {
  switch(rating) {
    case 5: return '#34c759'; // 绿色
    case 4: return '#30d158'; // 浅绿色
    case 3: return '#ffcc00'; // 黄色
    case 2: return '#ff9500'; // 橙色
    case 1: return '#ff3b30'; // 红色
    default: return '#8e8e93'; // 灰色
  }
}

// 当组件加载时初始化新图表
onMounted(() => {
  // 现有代码...
  
  // 初始化使用频率分布图表
  nextTick(() => {
    if (usageFrequencyChartRef.value) {
      const chart = echarts.init(usageFrequencyChartRef.value)
      chart.setOption({
        series: [
          {
            name: '使用频率',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: usageFrequencyDistribution.value.data.map(item => ({
              value: item.count,
              name: item.frequency,
              itemStyle: {
                color: item.color
              }
            }))
          }
        ]
      })
    }
  })
})

// 添加引用
const usageFrequencyChartRef = ref(null)
const channelConversionChartRef = ref(null)
const ratingChartRef = ref(null)

// Get monthly spending trend data from store or calculate (Rename this computed property)
const monthlySpendingTrendDataFromStore = computed(() => statisticsStore.getMonthlySpendingTrend)

// Define a separate ref for the average growth rate shown in the card
const averageGrowthRate = ref(12) // Initialize with the intended static value for now

// 获取状态颜色
const getStatusColor = (statusName) => {
  const statusColors = {
    '正常使用': '#34c759',
    '需要替换': '#ff9500',
    '需要维修': '#ff3b30',
    '已停用': '#a2a2a7',
    '已过期': '#ff3b30',
    '已损坏': '#ff3b30',
    '闲置': '#a2a2a7'
  }
  return statusColors[statusName] || '#8e8e93'
}

// 该函数已在前面定义，这里移除重复声明
// const getExpiredCount = () => {
//   const expiredStatus = stats.itemsByStatus.find(s => s.name === '已过期')
//   return expiredStatus ? expiredStatus.count : 0
// }

// 当timeRange变化时重新获取数据 - 这个在实际应用中应该触发API查询
watch(timeRange, async (newVal) => {
  changeTimeRange(newVal)
  // 在实际项目中，这里应该根据时间范围从API获取新数据
})

// 计算物品总价值
const calculateTotalValue = (items) => {
  return items.reduce((total, item) => {
    // 确保价格是数字且有效
    const price = parseFloat(item.price || 0);
    return isNaN(price) ? total : total + price;
  }, 0);
}

// 计算本月新增物品
const calculateNewItemsThisMonth = (items) => {
  const now = new Date();
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  
  return items.filter(item => {
    const purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : null;
    return purchaseDate && purchaseDate >= startOfMonth;
  }).length;
}

// 计算物品数量趋势(与上月比较)
const calculateItemsTrend = (items) => {
  const now = new Date();
  const startOfThisMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  
  const thisMonthItems = items.filter(item => {
    const purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : null;
    return purchaseDate && purchaseDate >= startOfThisMonth;
  }).length;
  
  const lastMonthItems = items.filter(item => {
    const purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : null;
    return purchaseDate && purchaseDate >= startOfLastMonth && purchaseDate < startOfThisMonth;
  }).length;
  
  // 防止除以零
  if (lastMonthItems === 0) return thisMonthItems > 0 ? 100 : 0;
  
  return Math.round((thisMonthItems - lastMonthItems) / lastMonthItems * 100);
}

// 计算物品价值趋势(与上月比较)
const calculateValueTrend = (items) => {
  const now = new Date();
  const startOfThisMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  
  const thisMonthValue = items
    .filter(item => {
      const purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : null;
      return purchaseDate && purchaseDate >= startOfThisMonth;
    })
    .reduce((total, item) => {
      const price = parseFloat(item.price || 0);
      return isNaN(price) ? total : total + price;
    }, 0);
  
  const lastMonthValue = items
    .filter(item => {
      const purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : null;
      return purchaseDate && purchaseDate >= startOfLastMonth && purchaseDate < startOfThisMonth;
    })
    .reduce((total, item) => {
      const price = parseFloat(item.price || 0);
      return isNaN(price) ? total : total + price;
    }, 0);
  
  // 防止除以零
  if (lastMonthValue === 0) return thisMonthValue > 0 ? 100 : 0;
  
  return Math.round((thisMonthValue - lastMonthValue) / lastMonthValue * 100);
}

// 计算顶级分类
const calculateTopCategories = (items) => {
  // 类别映射，用于累计每个类别的数量
  const categoryCounts = {};
  const categoryValues = {};
  
  // 更新：确保此处的颜色映射包含所有可能的类别
  const categoryColors = {
    '电子产品': '#007aff',
    '数码': '#007aff', // 与电子产品相同
    '家具': '#ff9500',
    '厨具': '#34c759', // 修改为厨具
    '厨房用品': '#34c759', // 与厨具相同
    '办公文具': '#5e5ce6',
    '生活用品': '#ff3b30',
    '首饰': '#af52de', // 添加首饰
    '美妆': '#ff2d55', // 添加美妆
    '工具': '#a2845e', // 添加工具
    '玩具': '#32ade6', // 添加玩具
    '运动': '#8e8e93', // 添加运动 - 暂时用灰色，可调整
    '家电': '#ffcc00', // 添加家电
    '其他': '#a2a2a7' // 保留其他
  };
  
  // 按类别统计物品数量和价值
  items.forEach(item => {
    const categoryName = item.categoryName || '其他';
    
    if (!categoryCounts[categoryName]) {
      categoryCounts[categoryName] = 0;
      categoryValues[categoryName] = 0;
    }
    
    categoryCounts[categoryName]++;
    categoryValues[categoryName] += parseFloat(item.price || 0);
  });
  
  // 转换为数组
  return Object.keys(categoryCounts).map(name => ({
    name,
    count: categoryCounts[name],
    value: categoryValues[name],
    color: categoryColors[name] || categoryColors['其他'] // 添加颜色属性
  })).sort((a, b) => b.count - a.count);
}

// 计算顶级位置
const calculateTopLocations = (items) => {
  // 位置映射，用于累计每个位置的数量
  const locationCounts = {};
  
  // 更新：确保包含 '家' 或其他实际位置名称
  const locationColors = {
    '客厅': '#007aff',
    '卧室': '#af52de',
    '厨房': '#ff9500',
    '卫生间': '#5ac8fa',
    '书房': '#ff3b30',
    '阳台': '#34c759',
    '储藏室': '#a2845e',
    '家': '#5856d6', // 添加 '家' 的颜色
    '其他': '#8e8e93'
  };
  
  // 按位置统计物品数量，优先使用 specificLocation
  items.forEach(item => {
    // 优先使用 specificLocation，如果不存在则回退到 locationName，再不存在则使用'其他'
    const locationName = item.specificLocation || item.locationName || '其他';
    
    if (!locationCounts[locationName]) {
      locationCounts[locationName] = 0;
    }
    
    locationCounts[locationName]++;
  });
  
  // 转换为数组
  return Object.keys(locationCounts).map(name => ({
    name,
    count: locationCounts[name],
    color: locationColors[name] || locationColors['其他'] // 添加颜色属性
  })).sort((a, b) => b.count - a.count);
}

// 计算物品状态分布
const calculateItemStatusDistribution = (items) => {
  // 获取所有状态及其计数
  const statusCounts = {};
  
  items.forEach(item => {
    // 状态可能来自item.statusLabel或根据其他属性计算
    let status = item.statusLabel || '正常使用';
    
    // 根据条件判断不同状态
    if (item.expiryDate) {
      const now = new Date();
      const expiryDate = new Date(item.expiryDate);
      
      if (expiryDate < now) {
        status = '已过期';
      } else if ((expiryDate - now) / (1000 * 60 * 60 * 24) < 30) {
        status = '即将过期';
      }
    }
    
    if (!statusCounts[status]) statusCounts[status] = 0;
    statusCounts[status]++;
  });
  
  // 状态颜色映射
  const statusColors = {
    '正常使用': '#34c759',
    '需要替换': '#ff9500',
    '需要维修': '#ff3b30',
    '已停用': '#a2a2a7',
    '已过期': '#ff3b30',
    '即将过期': '#ff9500',
    '闲置': '#5856d6',
    '已丢失': '#8e8e93',
    '其他': '#8e8e93'
  };
  
  // 转换为数组并排序
  const statusItems = Object.keys(statusCounts).map(name => ({
    name,
    count: statusCounts[name],
    percentage: (statusCounts[name] / items.length * 100).toFixed(1),
    color: statusColors[name] || '#8e8e93' // 添加颜色属性
  }));
  
  // 按计数降序排序
  return statusItems.sort((a, b) => b.count - a.count);
}

// 计算月度支出趋势
const calculateMonthlySpending = (items) => {
  const monthlyData = [];
  const now = new Date();
  
  // 生成过去12个月的月份
  for (let i = 11; i >= 0; i--) {
    const month = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const monthName = `${month.getMonth() + 1}月`;
    
    monthlyData.push({
      month: monthName,
      value: 0,
      count: 0
    });
  }
  
  // 填充每月支出数据
  items.forEach(item => {
    const purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : null;
    if (!purchaseDate) return;
    
    const price = parseFloat(item.price || 0);
    if (isNaN(price)) return;
    
    // 检查是否在过去12个月内
    const monthDiff = (now.getFullYear() - purchaseDate.getFullYear()) * 12 + now.getMonth() - purchaseDate.getMonth();
    if (monthDiff >= 0 && monthDiff < 12) {
      const index = 11 - monthDiff;
      monthlyData[index].value += price;
      monthlyData[index].count++;
    }
  });
  
  return monthlyData;
}

// 计算花销排行榜
const calculateSpendingRankList = (items) => {
  // 过滤有效价格的物品并排序
  return items
    .filter(item => item.price && !isNaN(parseFloat(item.price)))
    .map(item => ({
      name: item.name || '未命名物品',
      amount: parseFloat(item.price),
      purchaseDate: item.purchaseDate ? formatDate(new Date(item.purchaseDate)) : '未知'
    }))
    .sort((a, b) => b.amount - a.amount)
    .slice(0, 10); // 取前10个
}

// 计算持有天数排行榜
const calculateHoldingDaysRankList = (items) => {
  const now = new Date();
  
  // 计算每个物品的持有天数
  return items
    .filter(item => item.purchaseDate)
    .map(item => {
      const purchaseDate = new Date(item.purchaseDate);
      const daysDiff = Math.floor((now - purchaseDate) / (1000 * 60 * 60 * 24));
      
      return {
        name: item.name || '未命名物品',
        days: daysDiff
      };
    })
    .sort((a, b) => b.days - a.days)
    .slice(0, 5); // 取前5个
}

// 计算持有天数完整列表(包含更多详情)
const calculateHoldingDaysListFull = (items) => {
  const now = new Date();
  
  // 计算每个物品的持有天数及更多信息
  return items
    .filter(item => item.purchaseDate)
    .map(item => {
      const purchaseDate = new Date(item.purchaseDate);
      const daysDiff = Math.floor((now - purchaseDate) / (1000 * 60 * 60 * 24));
      const price = parseFloat(item.price || 0);
      
      return {
        name: item.name || '未命名物品',
        days: daysDiff,
        purchaseDate: formatDate(purchaseDate),
        frequency: item.frequency || '未记录',
        dailyCost: daysDiff > 0 && !isNaN(price) ? (price / daysDiff).toFixed(2) : '0.00'
      };
    })
    .sort((a, b) => b.days - a.days)
    .slice(0, 10); // 取前10个
}

// 计算购买渠道分布
const calculateChannelDistribution = (items) => {
  // 获取所有渠道及其金额
  const channelAmounts = {};
  let totalAmount = 0;
  
  // 渠道颜色映射
  const channelColors = {
    '京东': '#1976d2',
    '淘宝': '#ff9800',
    '拼多多': '#e91e63',
    '线下超市': '#43a047',
    '天猫': '#7e57c2',
    '苏宁': '#fbc02d',
    '其他': '#90caf9'
  };
  
  // 按渠道统计金额
  items.forEach(item => {
    const channel = item.purchaseChannel || '其他';
    const price = parseFloat(item.price || 0);
    
    if (isNaN(price)) return;
    
    if (!channelAmounts[channel]) channelAmounts[channel] = 0;
    channelAmounts[channel] += price;
    totalAmount += price;
  });
  
  // 转换为数组并计算百分比
  const channels = Object.keys(channelAmounts).map(name => {
    const amount = channelAmounts[name];
    return {
      name,
      amount: amount.toFixed(2),
      percent: totalAmount > 0 ? ((amount / totalAmount) * 100).toFixed(1) : '0.0',
      color: channelColors[name] || channelColors['其他'] // 使用内联的颜色映射
    };
  });
  
  // 按金额降序排序
  return channels.sort((a, b) => parseFloat(b.amount) - parseFloat(a.amount));
}

// 计算使用频率分布
const calculateUsageFrequency = (items) => {
  // 获取所有使用频率及其计数
  const frequencyCounts = {
    '每日': 0,
    '每周': 0,
    '每月': 0,
    '偶尔': 0,
    '很少': 0
  };
  
  items.forEach(item => {
    const frequency = item.frequency || '偶尔';
    if (frequencyCounts[frequency] !== undefined) {
      frequencyCounts[frequency]++;
    } else {
      frequencyCounts['偶尔']++;
    }
  });
  
  // 颜色映射
  const colorMap = {
    '每日': '#34c759',
    '每周': '#007aff',
    '每月': '#5856d6',
    '偶尔': '#ff9500',
    '很少': '#ff3b30'
  };
  
  // 转换为数组
  return Object.keys(frequencyCounts).map(name => ({
    name,
    count: frequencyCounts[name],
    color: colorMap[name] || '#8e8e93',
    id: name.toLowerCase()
  }));
}

// 计算物品评分数据 - 使用后端数据
const calculateItemRatings = (items) => {
  console.log('[calculateItemRatings] 开始处理后端物品评分数据，物品数量:', items.length);
  
  // 定义评分维度
  const dimensions = [
    '性价比',
    '耐用性',
    '外观',
    '实用性',
    '满意度'
  ];
  
  // 维度索引映射 - 如果后端数据包含对应的字段，可以直接使用
  const dimensionFields = [
    'pricePerformance', // 性价比
    'durability',       // 耐用性
    'appearance',       // 外观
    'practicality',     // 实用性
    'satisfaction'      // 满意度
  ];
  
  // 初始化类别评分对象
  const categoryRatings = {};

  // 类别特性权重映射 - 当评分数据不完整时用于分配权重
  const categoryWeights = {
    '电子产品': [1.1, 0.9, 1.0, 1.2, 0.8],
    '数码': [1.1, 0.9, 1.0, 1.2, 0.8],
    '家具': [0.8, 1.2, 1.1, 0.9, 1.0],
    '厨房用品': [0.9, 1.1, 0.8, 1.2, 1.0],
    '厨具': [0.9, 1.1, 0.8, 1.2, 1.0],
    '衣物': [0.8, 0.9, 1.3, 1.0, 1.0],
    '首饰': [0.7, 0.8, 1.4, 0.9, 1.2],
    '美妆': [0.8, 0.7, 1.3, 0.9, 1.3],
    '工具': [1.0, 1.3, 0.7, 1.2, 0.8],
    '玩具': [0.8, 0.9, 1.1, 1.2, 1.0],
    '运动': [0.9, 1.2, 0.9, 1.1, 0.9],
    '家电': [1.1, 1.2, 0.8, 1.1, 0.8],
    '其他': [1.0, 1.0, 1.0, 1.0, 1.0]
  };
  
  // 获取类别权重
  const getCategoryWeights = (category) => {
    return categoryWeights[category] || categoryWeights['其他'];
  };
  
  // 记录处理的物品信息
  let processedCount = 0;
  let fullRatingCount = 0;
  let partialRatingCount = 0;
  let noRatingCount = 0;
  
  // 检查后端数据中是否包含多维度评分数据
  let hasMultidimensionalRatings = false;
  
  // 处理每个物品的评分
  items.forEach(item => {
    const category = item.categoryName || '其他';
    
    // 确保类别存在于统计对象中
    if (!categoryRatings[category]) {
      categoryRatings[category] = {
        counts: 0,
        scores: [0, 0, 0, 0, 0] // 初始化5个维度的评分总和
      };
    }
    
    // 检查物品是否有评分数据
    if (item.rating) {
      processedCount++;
      categoryRatings[category].counts++;
      
      // 检查是否有详细的多维度评分
      const detailedRatings = 
        dimensionFields.map(field => item[field] ? parseFloat(item[field]) : null)
        .filter(rating => rating !== null);
      
      if (detailedRatings.length === dimensions.length) {
        // 物品有完整的多维度评分
        hasMultidimensionalRatings = true;
        fullRatingCount++;
        
        // 直接使用多维度评分
        dimensionFields.forEach((field, index) => {
          if (item[field]) {
            const rating = parseFloat(item[field]);
            if (!isNaN(rating)) {
              categoryRatings[category].scores[index] += rating;
            }
          }
        });
      } else if (detailedRatings.length > 0) {
        // 物品有部分多维度评分
        hasMultidimensionalRatings = true;
        partialRatingCount++;
        
        // 使用可用的维度评分，其他维度按权重分配
        const baseRating = parseFloat(item.rating);
        const weights = getCategoryWeights(category);
        
        dimensionFields.forEach((field, index) => {
          if (item[field]) {
            const rating = parseFloat(item[field]);
            if (!isNaN(rating)) {
              categoryRatings[category].scores[index] += rating;
            } else {
              // 该维度没有评分，使用基础评分按权重分配
              categoryRatings[category].scores[index] += baseRating * weights[index];
            }
          } else {
            // 该维度没有评分，使用基础评分按权重分配
            categoryRatings[category].scores[index] += baseRating * weights[index];
          }
        });
      } else {
        // 只有单一总评分
        const rating = parseFloat(item.rating);
        if (!isNaN(rating)) {
          const weights = getCategoryWeights(category);
          
          // 根据类别权重分配评分到各个维度
          for (let i = 0; i < 5; i++) {
            categoryRatings[category].scores[i] += rating * weights[i];
          }
        }
      }
    } else {
      // 物品没有评分
      noRatingCount++;
    }
  });
  
  console.log(`[calculateItemRatings] 处理统计:
    - 总处理物品: ${processedCount}
    - 完整多维度评分: ${fullRatingCount}
    - 部分多维度评分: ${partialRatingCount}
    - 无评分物品: ${noRatingCount}
    - 后端数据是否包含多维度评分: ${hasMultidimensionalRatings ? '是' : '否'}`);
  
  // 定义类别颜色
  const categoryColors = {
    '电子产品': '#007AFF',
    '数码': '#007AFF',
    '家具': '#A2845E',
    '厨房用品': '#FF9500',
    '厨具': '#FF9500',
    '衣物': '#AF52DE',
    '首饰': '#5AC8FA',
    '美妆': '#FF2D55',
    '工具': '#FF3B30',
    '玩具': '#34C759',
    '运动': '#5856D6',
    '家电': '#FFCB00',
    '其他': '#8E8E93'
  };

  // 生成结果
  const result = [];
  for (const category in categoryRatings) {
    // 如果类别有评分物品
    if (categoryRatings[category].counts > 0) {
      // 计算每个维度的平均分并保留一位小数
      const dimensionValues = categoryRatings[category].scores.map(score => 
        parseFloat((score / categoryRatings[category].counts).toFixed(1))
      );
      
      // 添加到结果数组
      result.push({
        name: category,
        value: dimensionValues, // 返回维度平均分数组
        color: categoryColors[category] || categoryColors['其他'],
        count: categoryRatings[category].counts  // 包含评分的物品数量
      });
    }
  }

  // 按平均总分降序排序
  const sortedResult = result.sort((a, b) => {
    const avgA = a.value.reduce((sum, val) => sum + val, 0) / a.value.length;
    const avgB = b.value.reduce((sum, val) => sum + val, 0) / b.value.length;
    return avgB - avgA;
  });
  
  console.log(`[calculateItemRatings] 返回 ${sortedResult.length} 个类别的评分数据`);
  
  // 如果没有评分数据，返回默认模拟数据
  if (sortedResult.length === 0) {
    console.log('[calculateItemRatings] 没有评分数据，使用默认模拟数据');
    return [
      {
        name: '电子产品',
        value: [4.8, 3.5, 4.2, 5.0, 3.8],
        color: '#007AFF',
        count: 0
      },
      {
        name: '家具',
        value: [3.9, 4.5, 3.2, 4.0, 4.5],
        color: '#A2845E',
        count: 0
      },
      {
        name: '厨房用品',
        value: [4.2, 4.8, 3.8, 3.5, 4.0],
        color: '#FF9500',
        count: 0
      },
      {
        name: '玩具',
        value: [3.8, 3.2, 4.5, 4.0, 4.3],
        color: '#34C759',
        count: 0
      }
    ];
  }
  
  return sortedResult;
};

// 计算过期物品
const calculateExpiryItems = (items) => {
  const now = new Date();
  const expiringList = [];
  const expiredList = [];
  
  items.forEach(item => {
    if (!item.expiryDate) return;
    
    const expiryDate = new Date(item.expiryDate);
    const daysLeft = Math.floor((expiryDate - now) / (1000 * 60 * 60 * 24));
    
    if (daysLeft < 0) {
      // 已过期
      expiredList.push({
        name: item.name || '未命名物品',
        expiryDate: formatDate(expiryDate),
        daysExpired: Math.abs(daysLeft)
      });
    } else if (daysLeft <= 30) {
      // 即将过期(30天内)
      expiringList.push({
        name: item.name || '未命名物品',
        expiryDate: formatDate(expiryDate),
        daysLeft: daysLeft
      });
    }
  });
  
  // 排序：已过期的按过期天数降序，即将过期的按剩余天数升序
  expiredList.sort((a, b) => b.daysExpired - a.daysExpired);
  expiringList.sort((a, b) => a.daysLeft - b.daysLeft);
  
  // 更新到组件数据
  expiringItems.value = expiringList;
  expiredItems.value = expiredList;
}

// 辅助函数：格式化日期
const formatDate = (date) => {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

// 清空统计数据的辅助函数
const clearStatisticsData = () => {
  stats.totalItems = 0;
  stats.totalValue = 0;
  stats.newItemsThisMonth = 0;
  stats.totalItemsTrend = 0;
  stats.totalValueTrend = 0;
  stats.topCategories = [];
  stats.topLocations = [];
  stats.monthlySpending = [];
  stats.itemsByStatus = [];
  
  // 清空图表数据
  spendingRankList.value = [];
  holdingDaysRankList.value = [];
  holdingDaysListFull.value = [];
  channelCategoryList.value = [];
  usageStats.value = [];
  itemRatingData.value = [];
  
  // 清空过期物品数据
  expiringItems.value = [];
  expiredItems.value = [];
}

// 添加一个辅助函数来获取类别的物品数量 (需要从 calculateItemRatings 返回count)
const getItemCountForCategory = (categoryName) => {
  // 临时的实现，后续需要修改 calculateItemRatings 返回 count
  const categoryData = itemRatingData.value.find(item => item.name === categoryName);
  // console.log(`Finding count for ${categoryName}:`, categoryData); // Debug log
  // 这里暂时无法获取真实的 count，因为 calculateItemRatings 目前没返回
  // 后续需要修改 calculateItemRatings 返回 { name, value, color, count }
  // 暂时返回 'N/A'
  // return categoryData ? categoryData.count : 'N/A';

  // 临时从原始 allItems 计算 count，效率较低但能工作
  const allItems = itemsStore.allItems; // 假设可以访问
  if (!allItems) return 'N/A';
  return allItems.filter(item => (item.categoryName || '其他') === categoryName && !isNaN(parseFloat(item.rating))).length;
};
</script>

<style scoped>
.statistics-view {
  min-height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0rem 0 1rem 4px;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.date-range-selector {
  min-width: 200px;
  margin-right: 4px;
}

.time-select {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  backdrop-filter: blur(10px);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid rgba(0, 113, 227, 0.1);
  border-top-color: #0071e3;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 网格布局 */
.stats-grid {
    display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 0 4px 16px;
}

/* 卡片基础样式 */
.stats-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  display: flex;
  flex-direction: column;
  position: relative;
  aspect-ratio: 1 / 1;
  transition: all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-origin: center;
  transform: scale(1) translateY(0);
  overflow: hidden;
  cursor: pointer;
}

.stats-card:hover {
  transform: translateY(-6px) scale(1.02);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.stats-card:active {
  transform: translateY(0) scale(0.97);
  transition: all 0.15s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.card-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 12px;
}

/* 总花销卡片 */
.total-spending {
  background-color: #fffbe6;
  border: 2px solid #ffe58f;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.total-spending .card-title {
  color: #d48806;
  font-size: 1.2rem;
  margin-bottom: 16px;
}

.total-value {
  font-size: 2.5rem;
  font-weight: bold;
  color: #fa8c16;
  margin-bottom: 16px;
}

.card-action {
  padding: 8px 16px;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 20px;
  font-size: 0.85rem;
  color: #666;
  margin-top: auto;
  cursor: pointer;
  transition: background-color 0.2s;
}

.card-action:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

/* 概览卡片 */
.stats-card .card-icon {
  width: 42px;
  height: 42px;
    border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.stats-card .card-value {
  font-size: 1.75rem;
  font-weight: 600;
  color: #1d1d1f;
  margin-top: 8px;
}

.stats-card .card-trend {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 0.85rem;
}

.trend-up {
  background-color: rgba(52, 199, 89, 0.1);
  color: #34c759;
}

.trend-down {
  background-color: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

/* 图表卡片 */
.chart-card .chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
    overflow: hidden;
}

.pie-chart, .line-chart, .funnel-chart, .radar-chart {
  height: 65%;
  width: 100%;
}

.chart-legend {
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow-y: auto;
  height: 35%;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 0.85rem;
}

.color-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 6px;
}

.legend-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 4px;
}

.legend-value {
  font-weight: 500;
}

/* 排行榜卡片 */
.rank-card .rank-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto; /* 保持滚动功能 */
  /* 添加以下样式隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none;  /* Internet Explorer 10+ */
}

/* 隐藏 WebKit 浏览器的滚动条 */
.rank-card .rank-list::-webkit-scrollbar {
  display: none;
}

.rank-item {
  display: flex;
  align-items: center;
  padding: 6px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.rank-item:last-child {
  border-bottom: none;
}

.rank-index {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f5f5f7;
  font-weight: bold;
  font-size: 0.9rem;
  margin-right: 12px;
}

.rank-index.top-rank {
  color: white;
}

.rank-index.top-rank:nth-child(1) { /* Check if this nth-child works as intended */
  background-color: #f5a623;
}

.rank-index.top-rank:nth-child(2) { /* Check if this nth-child works as intended */
  background-color: #b0bec5;
}

.rank-index.top-rank:nth-child(3) { /* Check if this nth-child works as intended */
  background-color: #bf8970;
}

.rank-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rank-name {
  font-size: 0.95rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 130px;
}

.rank-value {
  font-weight: 500;
  color: #666;
  font-size: 0.9rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }

  .date-range-selector {
    width: 100%;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
  
  .modal-container {
    width: 95%;
    height: 90vh;
  }
  
  .detail-data-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(5px);
  will-change: opacity;
}

.modal-container {
  background-color: #fff;
  width: 90%;
  max-width: 1200px;
  height: 85vh;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  will-change: transform, opacity;
  transform-origin: center;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.modal-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1d1d1f;
    margin: 0;
}

.modal-close {
  background: none;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  transition: background-color 0.2s;
}

.modal-close:hover {
  background-color: rgba(18, 18, 19, 0.05);
}

.modal-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.modal-loading {
  pointer-events: none;
}

.modal-loading-indicator {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 模态框动画 */
.modal-enter-active {
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.modal-leave-active {
  transition: all 0.3s cubic-bezier(0.6, -0.28, 0.735, 0.045);
}

.modal-enter-from .modal-container {
  transform: scale(0.7);
  opacity: 0;
}

.modal-enter-to .modal-container {
  transform: scale(1);
  opacity: 1;
}

.modal-leave-from .modal-container {
  transform: scale(1);
  opacity: 1;
}

.modal-leave-to .modal-container {
  transform: scale(0.85);
  opacity: 0;
}

.modal-enter-from, .modal-leave-to {
  opacity: 0;
}

.modal-enter-to, .modal-leave-from {
  opacity: 1;
}

/* 详情内容样式 */
.detail-section {
  margin-bottom: 32px;
}

.detail-header {
    display: flex;
    justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: #1d1d1f;
}

.big-number-display {
  text-align: center;
  margin-bottom: 24px;
}

.big-number {
  font-size: 3.5rem;
  font-weight: bold;
  color: #fa8c16;
}

.big-number-label {
  font-size: 1rem;
    color: #666;
  margin-top: 4px;
}

.detail-chart-container {
  height: 300px;
  margin-bottom: 24px;
}

.detail-chart-large {
  height: 400px;
  margin-bottom: 24px;
}

.detail-data-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.detail-data-table table {
  width: 100%;
  border-collapse: collapse;
}

.detail-data-table th, 
.detail-data-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.detail-data-table th {
  background-color: #f7f7f7;
  font-weight: 600;
  color: #444;
}

.detail-data-table tr:last-child td {
    border-bottom: none;
}

.text-green {
  color: #34c759;
}

.text-red {
  color: #ff3b30;
}

.detail-data-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.detail-data-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.data-card-header {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.data-card-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.data-card-title {
  font-weight: 500;
}

.data-card-body {
  padding: 16px;
  text-align: center;
}

.data-card-amount {
  font-size: 1.5rem;
    font-weight: bold;
  margin-bottom: 4px;
}

.data-card-percent {
    color: #666;
}

.detail-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
}

.detail-placeholder .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.detail-placeholder p {
  font-size: 1.1rem;
}

/* 在原有的卡片样式上添加点击状态指示 */
.stats-card::after {
  content: "";
  position: absolute;
  top: 8px;
  right: 8px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: rgba(0, 113, 227, 0.6);
  opacity: 0;
  transition: opacity 0.2s;
}

.stats-card:hover::after {
  opacity: 1;
}

/* 综合统计卡片样式 */
.combined-stats {
  padding: 20px;
  background-color: #f8f9fa;
  border-left: 4px solid #0071e3;
}

.combined-stats-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: calc(100% - 40px);
}

.combined-stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.2s;
}

.combined-stat-item:hover {
  transform: translateX(3px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 42px;
  height: 42px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
  width: fit-content;
  padding: 2px 6px;
  border-radius: 10px;
}

/* 添加新的样式 */
.expiry-details {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.expiry-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #666;
}

.expiry-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

/* 新增详情视图样式 */
.combined-stats-detail {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.detail-data-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  overflow: hidden;
}

.data-card-header {
  display: flex;
  align-items: center;
  padding: 16px;
  gap: 10px;
}

.data-card-icon {
  width: 42px;
  height: 42px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.data-card-title {
    font-size: 16px;
  font-weight: 500;
}

.data-card-body {
  padding: 16px;
}

.data-card-amount {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.data-card-trend {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 20px;
  width: fit-content;
}

.data-card-chart {
  height: 100px;
}

.monthly-detail {
  display: flex;
  margin-top: 10px;
}

.monthly-chart {
  flex: 1;
  height: 80px;
}

.monthly-stats {
  width: 120px;
  padding: 0 10px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.detail-data-table {
  grid-column: span 2;
  margin-top: 20px;
}

.detail-data-table h4 {
  margin-bottom: 10px;
    color: #333;
}

.usage-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 15px;
  margin-top: 30px;
}

.usage-stat-card {
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  border-left: 4px solid transparent;
  transition: transform 0.2s;
}

.usage-stat-card:hover {
  transform: translateY(-3px);
}

.usage-stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.usage-stat-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.usage-stat-name {
  font-weight: 500;
}

.usage-stat-count {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 5px;
}

.usage-stat-percent {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.usage-stat-action {
  font-size: 13px;
  color: #0071e3;
}

.usage-recommendations {
  margin-top: 30px;
}

.recommendation-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.recommendation-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 10px;
}

.recommendation-icon {
  font-size: 24px;
  color: #ff9500;
}

.recommendation-title {
  font-weight: 500;
  margin-bottom: 5px;
}

.conversion-detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 15px;
  margin-top: 30px;
}

.conversion-card {
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  text-align: center;
}

.conversion-step {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.conversion-name {
  font-weight: 500;
  margin-bottom: 10px;
}

.conversion-value {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 5px;
}

.conversion-rate {
  font-size: 14px;
  color: #666;
}

.conversion-analysis {
  margin-top: 30px;
}

.rating-breakdown {
  margin-top: 30px;
}

.rating-dimension-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.rating-dimension {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 10px;
}

.dimension-name {
  font-weight: 500;
  margin-bottom: 15px;
}

.dimension-bars {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.dimension-bar-item {
  display: flex;
  align-items: center;
}

.dimension-label {
  width: 100px;
  font-size: 14px;
}

.dimension-bar-container {
  flex: 1;
  height: 20px;
  background-color: #eee;
  border-radius: 10px;
  position: relative;
  overflow: hidden;
}

.dimension-bar {
  height: 100%;
  border-radius: 10px;
}

.dimension-score {
  position: absolute;
  right: 10px;
  top: 0;
  font-size: 12px;
  font-weight: 500;
  color: #fff;
  height: 100%;
  display: flex;
  align-items: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .combined-stats-detail {
    grid-template-columns: 1fr;
  }
  
  .detail-data-table {
    grid-column: span 1;
  }
}

/* 过期物品详情样式 */
.expiry-summary {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.expiry-stat-card {
  flex: 1;
  background-color: white;
  border-radius: 12px;
    padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  display: flex;
  align-items: center;
  gap: 15px;
}

.expiry-stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 10px;
    display: flex;
  align-items: center;
  justify-content: center;
}

.expiry-stat-icon .el-icon {
  font-size: 30px;
}

.expiry-stat-content {
  flex: 1;
}

.expiry-stat-label {
  font-size: 16px;
  color: #666;
  margin-bottom: 5px;
}

.expiry-stat-value {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 5px;
}

.expiry-stat-desc {
  font-size: 13px;
  color: #999;
}

.expiry-chart-container {
  height: 300px;
  margin-bottom: 30px;
}

.expiry-list-title {
  margin: 20px 0 10px;
  color: #333;
}

.expiry-item-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.expiry-item {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  padding: 12px 16px;
  border-radius: 8px;
  border-left: 4px solid #ff9500;
}

.expiry-item.expired {
  border-left-color: #ff3b30;
}

.expiry-item-name {
  flex: 1;
  font-weight: 500;
}

.expiry-item-date {
  margin: 0 15px;
  color: #666;
}

.expiry-item-days {
  margin-right: 15px;
  font-weight: 500;
  color: #ff9500;
}

.expiry-item.expired .expiry-item-days {
  color: #ff3b30;
}

/* 购买渠道分布详情样式 */
.channel-chart-container {
  height: 350px;
  margin-bottom: 30px;
}

.channel-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.channel-stat-card {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.channel-stat-header {
  padding: 12px 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.channel-stat-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.channel-stat-name {
  font-weight: 500;
}

.channel-stat-body {
  padding: 12px 15px;
  text-align: center;
}

.channel-stat-amount {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 5px;
}

.channel-stat-percent {
  font-size: 14px;
  color: #666;
}

.channel-trend {
  margin-bottom: 30px;
}

.channel-trend h4, .channel-table h4 {
    margin-bottom: 15px;
  color: #333;
}

.channel-trend-chart {
  height: 300px;
}

.channel-table table {
  width: 100%;
  border-collapse: collapse;
}

.channel-table th, 
.channel-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.channel-table th {
  background-color: #f7f7f7;
  font-weight: 600;
  color: #444;
}

.channel-table tr:last-child td {
    border-bottom: none;
}

/* 物品花销排行详情样式 */
.rank-filter {
  display: flex;
  align-items: center;
}

.spending-rank-chart {
  height: 350px;
  margin-bottom: 30px;
}

.spending-rank-table {
  margin-bottom: 30px;
}

.spending-rank-table table {
  width: 100%;
  border-collapse: collapse;
}

.spending-rank-table th, 
.spending-rank-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.spending-rank-table th {
  background-color: #f7f7f7;
  font-weight: 600;
  color: #444;
}

.rank-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #f0f0f0;
  font-weight: 600;
}

.rank-number.top-rank {
  color: white;
}

.rank-number.top-rank:nth-child(1) { /* Check if this nth-child works */
  background-color: #f5a623;
}

.rank-number.top-rank:nth-child(2) { /* Check if this nth-child works */
  background-color: #b0bec5;
}

.rank-number.top-rank:nth-child(3) { /* Check if this nth-child works */
  background-color: #bf8970;
}

.percent-bar-container {
  width: 100%;
  height: 10px;
  background-color: #f0f0f0;
  border-radius: 5px;
  position: relative;
}

.percent-bar {
  height: 100%;
  background-color: #0071e3;
  border-radius: 5px;
}

.percent-bar-container span {
  position: absolute;
  right: 0;
  top: -18px;
  font-size: 12px;
    color: #666;
}

.spending-category-distribution {
  margin-bottom: 20px;
}

.spending-category-distribution h4 {
  margin-bottom: 15px;
  color: #333;
}

.spending-category-chart {
  height: 300px;
}

@media (max-width: 768px) {
  .channel-stats-grid {
    grid-template-columns: 1fr;
  }
  
  .rank-filter {
    margin-top: 10px;
  }
  
  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}

/* 持有天数排行详情样式 */
.holding-days-chart {
  height: 350px;
  margin-bottom: 30px;
}

.holding-days-stats {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.stats-card {
  flex: 1;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  text-align: center;
}

.stats-card-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #0071e3;
}

.stats-card-label {
  font-size: 14px;
  color: #666;
}

.holding-days-table {
  margin-bottom: 30px;
}

.holding-days-table h4, .holding-days-distribution h4 {
  margin-bottom: 15px;
  color: #333;
}

.holding-days-table table {
  width: 100%;
  border-collapse: collapse;
}

.holding-days-table th, 
.holding-days-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.holding-days-table th {
  background-color: #f7f7f7;
  font-weight: 600;
  color: #444;
}

.holding-days-distribution-chart {
  height: 300px;
}

/* 物品类别分布详情样式 */
.category-chart-container {
  height: 350px;
  margin-bottom: 30px;
}

.category-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.category-stat-card {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.category-stat-header {
  padding: 12px 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-stat-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.category-stat-name {
  font-weight: 500;
}

.category-stat-body {
  padding: 12px 15px;
}

.category-stat-count {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 5px;
}

.category-stat-value, .category-stat-percent {
  font-size: 14px;
  color: #666;
  margin-bottom: 3px;
}

.category-trends, .category-value-chart {
  margin-bottom: 30px;
}

.category-trends h4, .category-value-chart h4 {
  margin-bottom: 15px;
  color: #333;
}

.category-trend-chart, .category-value-chart-container {
  height: 300px;
}

@media (max-width: 768px) {
  .holding-days-stats {
    flex-wrap: wrap;
  }
  
  .stats-card {
    flex: 1 0 calc(50% - 10px);
  }
  
  .category-stats-grid {
    grid-template-columns: 1fr;
  }
}

/* 新增使用频率总览卡片样式 */
.usage-summary-card {
  padding: 16px;
  background-color: #f0f2f5; /* 浅灰色背景 */
}

.usage-summary-card .card-title {
  margin-bottom: 12px;
  text-align: center;
}

.usage-summary-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(4, 1fr);
  gap: 10px;
  margin-bottom: 10px;
}

.usage-summary-item {
  border-radius: 8px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: white; 
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  transition: transform 0.2s;
}

.usage-summary-item:hover {
  transform: scale(1.03);
}

.usage-item-label {
  font-size: 0.85rem;
  font-weight: 500;
  margin-bottom: 6px;
  opacity: 0.9;
}

.usage-item-count {
  font-size: 1.8rem;
    font-weight: bold;
  margin-bottom: 8px;
}

.usage-item-action {
  font-size: 0.8rem;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 3px 8px;
  border-radius: 12px;
}

/* 占位内容样式 */
.chart-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(245, 247, 250, 0.7);
  border-radius: 8px;
}

.placeholder-icon {
  font-size: 36px;
  color: #909399;
  margin-bottom: 10px;
}

.placeholder-text {
  font-size: 14px;
  color: #606266;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .usage-summary-grid {
    grid-template-columns: 1fr;
    grid-template-rows: auto;
  }
}

/* 添加以下样式 */

/* 使用频率分布卡片样式 */
.usage-frequency-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 购买渠道转化卡片样式 */
.conversion-stats {
  padding: 10px 0;
}

.conversion-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.conversion-platform {
  width: 80px;
  font-size: 14px;
  font-weight: 500;
}

.conversion-progress {
  flex: 1;
  height: 8px;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
  margin: 0 15px;
}

.dark-mode .conversion-progress {
  background-color: rgba(255, 255, 255, 0.1);
}

.progress-bar {
  height: 100%;
  border-radius: 4px;
}

.conversion-rate {
  width: 40px;
  font-size: 14px;
  text-align: right;
  font-weight: 500;
}

/* 评分分析卡片样式 */
.rating-chart {
  padding: 10px 0;
  display: flex;
  flex-direction: column;
}

.rating-summary {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.average-rating {
  font-size: 32px;
  font-weight: 600;
  color: #ff9500;
}

.rating-text {
  font-size: 14px;
  color: var(--apple-text-secondary-light);
  margin: 5px 0;
}

.dark-mode .rating-text {
  color: var(--apple-text-secondary-dark);
}

.rating-stars {
  display: flex;
  font-size: 18px;
}

.rating-bars {
  margin-top: 10px;
}

.rating-bar-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.rating-label {
  width: 40px;
  font-size: 13px;
}

.rating-bar {
  flex: 1;
  height: 8px;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
  margin: 0 10px;
}

.dark-mode .rating-bar {
  background-color: rgba(255, 255, 255, 0.1);
}

.rating-bar-fill {
  height: 100%;
  border-radius: 4px;
  background-color: #ff9500;
}

.rating-percentage {
  width: 40px;
  font-size: 13px;
  text-align: right;
}

/* 月度支出趋势卡片样式 */
.monthly-trend {
  width: 100%;
  height: 180px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  padding: 20px 0;
}

.trend-bar {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  height: 180px;
  position: relative;
}

.trend-bar-fill {
  width: 20px;
  border-radius: 10px 10px 0 0;
  transition: height 0.3s ease;
}

.trend-month {
  position: absolute;
  bottom: -20px;
  font-size: 12px;
  color: var(--apple-text-secondary-light);
}

.dark-mode .trend-month {
  color: var(--apple-text-secondary-dark);
}

/* 宽卡片样式 */
.wide-card {
  grid-column: span 2;
}

@media (max-width: 768px) {
  .wide-card {
    grid-column: span 1;
  }
}

/* 使用频率分布卡片样式 */
.usage-frequency-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.stats-card .pie-chart {
  height: 180px;
  width: 100%;
}

.chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.usage-legend {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 10px;
  gap: 10px;
}

.usage-legend-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.usage-legend-color {
  width: 10px;
  height: 10px;
  border-radius: 2px;
  margin-right: 5px;
}

.location-stat-card-alt {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  display: flex;
  flex-direction: column;
  position: relative;
  aspect-ratio: 1 / 1;
  transition: all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-origin: center;
  transform: scale(1) translateY(0);
  overflow: hidden;
  cursor: pointer;
}

.location-stat-card-alt:hover {
  transform: translateY(-6px) scale(1.02);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.location-stat-card-alt:active {
  transform: translateY(0) scale(0.97);
  transition: all 0.15s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.location-stat-alt-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.location-stat-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.location-stat-name {
  font-weight: 500;
}

.location-stat-body {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.location-stat-count {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1d1d1f;
}

.location-stat-percent {
  font-size: 12px;
  color: #666;
}

.location-stat-space {
  font-size: 12px;
  color: #666;
}

/* 位置分布详情样式 */
.location-chart-container {
  height: 250px; /* 减小图表容器高度 */
  margin-bottom: 20px;
}

.location-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); /* 尝试容纳更多列 */
  gap: 12px; /* 减小间距 */
  margin-bottom: 20px;
}

.location-stat-card {
  background-color: white;
  border-radius: 8px; /* 减小圆角 */
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06); /* 减小阴影 */
  padding: 12px; /* 减小内边距 */
}

.location-stat-header {
  padding: 0; /* 移除头部内边距 */
  margin-bottom: 8px; /* 减小间距 */
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: transparent !important; /* 强制移除背景色 */
}

.location-stat-color {
  width: 10px; /* 减小圆点大小 */
  height: 10px;
  border-radius: 50%;
}

.location-stat-name {
  font-weight: 500;
  font-size: 0.9rem; /* 减小字体 */
}

.location-stat-body {
  display: flex;
  flex-direction: column;
  gap: 5px; /* 减小内部间距 */
}

.location-sublocations,
.location-optimization {
  /* ... existing code ... */
}

/* 月度支出趋势详情样式 */
.spending-trend-chart {
  height: 280px; /* 调整主图表高度 */
  margin-bottom: 20px;
}

.spending-stats {
  display: flex;
  gap: 12px; /* 减小卡片间距 */
  margin-bottom: 20px; /* 减小下方间距 */
  flex-wrap: wrap; /* 允许换行 */
}

/* 调整详情弹窗内的 stats-card */
.modal-content .stats-card {
  flex: 1 1 calc(25% - 10px); /* 尝试每行放4个，减去间隙 */
  min-width: 150px; /* 设置最小宽度 */
  background-color: white;
  border-radius: 8px;
  padding: 12px; /* 减小内边距 */
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  text-align: center;
  /* 移除之前可能继承的 aspect-ratio */
  aspect-ratio: unset;
  cursor: default; /* 详情卡片通常不可点击 */
}

.modal-content .stats-card:hover {
  transform: none; /* 移除 hover 效果 */
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}

.modal-content .stats-card-value {
  font-size: 1.4rem; /* 减小字体 */
  font-weight: 600;
  margin-bottom: 4px;
  color: #0071e3;
}

.modal-content .stats-card-label {
  font-size: 0.8rem; /* 减小字体 */
  color: #666;
}

.spending-table {
  margin-bottom: 20px;
}

.spending-table h4 {
  margin-bottom: 10px;
  color: #333;
}

.spending-table table {
  width: 100%;
  border-collapse: collapse;
}

.spending-table th,
.spending-table td {
  padding: 10px 12px; /* 减小表格内边距 */
  text-align: left;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  font-size: 0.85rem; /* 减小表格字体 */
}

.spending-table th {
  background-color: #f7f7f7;
  font-weight: 600;
  color: #444;
}

.spending-forecast {
  margin-bottom: 20px;
}

.spending-forecast h4 {
  margin-bottom: 10px;
  color: #333;
}

.spending-forecast-chart {
  height: 200px; /* 调整预测图表高度 */
}

/* 物品状态分布详情样式 */
/* ... existing code ... */

/* 确保所有 CSS 注释使用正确的语法 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

/* ... existing code ... */

/* 物品状态分布详情样式 */
/* ... existing code ... */

/* 物品状态分布详情样式 */
/* 状态卡片样式 */
.status-stat-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.status-stat-header {
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-chart-container {
  height: 280px; /* 确保图表容器有明确的高度 */
  width: 100%;
  margin-bottom: 20px;
}

.location-chart-container {
  height: 280px; /* 确保图表容器有明确的高度 */
  width: 100%;
  margin-bottom: 20px;
}

.spending-trend-chart {
  height: 280px; /* 确保图表容器有明确的高度 */
  width: 100%;
  margin-bottom: 20px;
}

.detail-chart-large {
  height: 280px; /* 确保图表容器有明确的高度 */
  width: 100%;
  margin-bottom: 20px;
}

/* 修改弹窗样式，确保图表显示空间充足 */
.modal-container {
  max-width: 900px; /* 增加最大宽度 */
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}
</style>